大家好,我是天空之城,今天给大家带来,表的自连接的运用
自连接是一一种特殊的表连接,它是指相互连接的表在物理上同为一张表,但是逻辑上是多张表。自连接通常用于表中的数据有层次结构,如区域表、菜单表、商品分类表等。
#自连接语法
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 | 深圳 | 广东省 |
+----+------+--------------+