MySQL-自关联介绍-2021/09/16

过了10天才继续看MySQL希望看完别半途而废

自关联介绍


只要有上下级关系的都存在一个表中,有两个字段,一个是编号,一个是上级编号。这样就可以满足要求。
在这里插入图片描述
构造数据

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');

-- 添加区县数据
insert into areas values
('410101', '中原区', '410100'),
('410102', '二七区', '410100'),
('410103', '金水区', '410100');

练习题:
在这里插入图片描述
查询两个表,复制areas然后粘贴道表中

在这里插入代码片
  1. 查询有多少个省?
SELECT COUNT(*) FROM areas WHERE pid is null;

例1:查询河南省的所有城市 单极跳跃

SELECT * FROM areas , areas_copy1

在这里插入图片描述
然后让areas.aid = areas_copy1.pid 找到与省具有从属关系的数据

SELECT * FROM areas , areas_copy1
where areas.aid = areas_copy1.pid 

然后再用and进行查询areas.aid = '河南省’进行筛选

SELECT * FROM areas , areas_copy1
where areas.aid = areas_copy1.pid
and areas.atitle = '河南省'

在这里插入图片描述
这样查询显然是费事的,要复制一个表。其实可以对一个表进行两次查询。但是要给表起一个别名。

select
*
from
areas as p
inner join areas as c on c.pid=p.aid
where
p.atitle='河北省';

利用内连接

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

例2:查询郑州市的所有区县 单极跳跃

select 
*
from
areas c, areas q
where c.aid = q.pid
and c.atitle = '郑州市'

例3:查询河南省的所有区县 两级跳跃

再连接一个区的表

select 
*
from
areas sheng, areas shi, areas qu
where sheng.aid = shi.pid
and shi.aid = qu.pid
and sheng.atitle = '河南省'

利用左连接

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='河南省'
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值