立即学习:https://edu.csdn.net/course/play/27328/370701?utm_source=blogtoedu
自连接:一种特殊的表连接,是指相互连接的表在物理上同为一张表,但在逻辑上是多张表。自连接常用于表中的数据又层次结构,如区域表、菜单表、商品分类表等。
语法:
select A.column,B.column from table A,table B where A.column = B.column;
area表:
+----+-----+--------+
| id | pid | name |
+----+-----+--------+
| 1 | 0 | 贵州省 |
| 2 | 1 | 贵阳 |
| 3 | 1 | 遵义 |
| 4 | 0 | 广东省 |
| 5 | 4 | 广州 |
| 6 | 4 | 深圳 |
+----+-----+--------+
省份pid为0,城市pid为省份的id
城市表关联省份表:
select A.id, A.name, B.name as provienceName
from area A,area B
where A.pid = B.id and A.pid <>0;
+----+------+---------------+
| id | name | provienceName |
+----+------+---------------+
| 2 | 贵阳 | 贵州省 |
| 3 | 遵义 | 贵州省 |
| 5 | 广州 | 广东省 |
| 6 | 深圳 | 广东省 |
+----+------+---------------+