我们要做一个全国的区域选择 包括 省 市 区…
这样的三张表 可以合并为一张表
在一个表中,一列用到了另一列的值 ,叫做自关联。
自关联一般用作省市县、公司上下级、
-- 创建一个新的表格 areas
create table areas(
aid int primary key,
atitle varchar(20),
pid int
);
-- 插入数据
insert into areas values(10000, '河北省', null);
insert into areas values(10001, '北京市', 10000);
insert into areas values(10002, '山东省', null);
insert into areas values(10003, '青岛市', 10002);
insert into areas values(10004, '崂山区', 10003);
...
如何讲一个文件数据插入到表中,首先放在同一个路径下,然后打开所在数据库。
然后: 文件名是 areas.sql
source areas.sql
--查询所有的省份
select * from areas where pid is null;
--查看山东省有多少地级市
--先找到山东的aid
select aid from areas where atitle='山东省'
--查看山东省有多少地级市
select * from areas where pid=370000;
同样还能接着查青岛市有多少区 pid=370200
刚刚是用了两步查出来的,那么能不能用一个步骤就能查出来?
select * from areas as province inner join areas as city on city.pid=province.aid having province.atitle='山东省';
山东省改为青岛市:
--子查询 一个查询中 嵌套另一个查询
-- 标量子查询
--查询出最高的男生信息
select * from students where height=(select max(height) from students);