MySQL学习笔记,表的自连接运用

大家好,我是天空之城,今天给大家带来,表的自连接的运用

自连接是一一种特殊的表连接,它是指相互连接的表在物理上同为一张表,但是逻辑上是多张表。自连接通常用于表中的数据有层次结构,如区域表、菜单表、商品分类表等。
#自连接语法
SELECT A.column, B.column
FROM table A, table B
WHERE A.column = B.column;

先建表
drop table if exists area;
drop table if exists area;

create table area(
	id int not null auto_increment primary key comment '区域id',
	pid int not null comment '父id(0-省份)',
	name varchar(30) comment '区域名称'
);

insert into area(id, pid, name) values(1, 0, '贵州省');
insert into area(id, pid, name) values(2, 1, '贵阳');
insert into area(id, pid, name) values(3, 1, '遵义');
insert into area(id, pid, name) values(4, 0, '广东省');
insert into area(id, pid, name) values(5, 4, '广州');
insert into area(id, pid, name) values(6, 4, '深圳');

mysql> select * from area;
+----+-----+--------+
| id | pid | name   |
+----+-----+--------+
|  1 |   0 | 贵州省 |
|  2 |   1 | 贵阳   |
|  3 |   1 | 遵义   |
|  4 |   0 | 广东省 |
|  5 |   4 | 广州   |
|  6 |   4 | 深圳   |
+----+-----+--------+

找出不是省份的城市
mysql> select * from area where pid<>0;
+----+-----+------+
| id | pid | name |
+----+-----+------+
|  2 |   1 | 贵阳 |
|  3 |   1 | 遵义 |
|  5 |   4 | 广州 |
|  6 |   4 | 深圳 |
+----+-----+------+
4 rows in set (0.00 sec)

找到城市对应各自省份
mysql> select A.id, A.name, B.name as  provincename
    -> from area A ,area B
    -> where A.pid = B.id and A.pid<>0;
+----+------+--------------+
| id | name | provincename |
+----+------+--------------+
|  2 | 贵阳 | 贵州省       |
|  3 | 遵义 | 贵州省       |
|  5 | 广州 | 广东省       |
|  6 | 深圳 | 广东省       |
+----+------+--------------+


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值