查询之自关联

自关联

  • 设计省信息的表结构provinces
    • id
    • ptitle
  • 设计市信息的表结构citys
    • id
    • ctitle
    • proid
  • citys表的proid表示城市所属的省,对应着provinces表的id值
  • 问题:能不能将两个表合成一张表呢?
  • 思考:观察两张表发现,citys表比provinces表多一个列proid,其它列的类型都是一样的
  • 意义:存储的都是地区信息,而且每种信息的数据量有限,没必要增加一个新表,或者将来还要存储区、乡镇信息,都增加新表的开销太大
  • 答案:定义表areas,结构如下
    • id
    • atitle
    • pid
  • 因为省没有所属的省份,所以可以填写为null
  • 城市所属的省份pid,填写省所对应的编号id
  • 这就是自关联,表中的某一列,关联了这个表中的另外一列,但是它们的业务逻辑含义是不一样的,城市信息的pid引用的是省信息的id
  • 在这个表中,结构不变,可以添加区县、乡镇街道、村社区等信息

准备数据:

create table areas(
aid int primary key,
atitle varchar(20),
pid int
);

insert into areas 
values ('130000', '河北省', NULL),
('130100', '石家庄市', '130000'),
('130400', '邯郸市', '130000'),
('130600', '保定市', '130000'),
('130700', '张家口市', '130000'),
('130800', '承德市', '130000'),
('410000', '河南省', NULL),
('410100', '郑州市', '410000'),
('410300', '洛阳市', '410000'),
('410500', '安阳市', '410000'),
('410700', '新乡市', '410000'),
('410800', '焦作市', '410000');
  • 例1:查询一共有多少个省
select count(*) from areas where pid is null;

例1:查询河南省的所有城市

select 
    * 
from 
    areas as p
inner join areas as c on c.pid=p.aid
where 
    p.atitle='河北省';
添加区县数据

insert into areas values
('410101', '中原区', '410100'),
('410102', '二七区', '410100'),
('410103', '金水区', '410100');

例2:查询郑州市的所有区县

select 
    * 
from 
    areas as c
inner join areas as a on a.pid=c.aid
where 
    c.atitle='郑州市';

例3:查询河南省的所有区县

select 
    * 
from 
    areas as p
left join areas as c on c.pid=p.aid
left join areas as a on a.pid=c.aid
where 
    p.atitle='河南省'
发布了240 篇原创文章 · 获赞 77 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/dpl12/article/details/104196998