建表:
create table `pid`(
`id` int(5) not null AUTO_INCREMENT,
`name` varchar(10) not null,
`pid` int(5) not null,
primary key(`id`)
)ENGINE=INNODB DEFAULT CHARSET=utf8;
插入数据:
insert into `pid` VALUES
(1,'吉林省',0),
(2,'江苏省',0),
(3,'浙江省',0),
(4,'南京市',2),
(5,'杭州市',3),
(6,'长春市',1),
(7,'淮安市',1),
(8,'温州市',3),
(9,'嘉兴市',3),Í
(10,'白山市',1),
(11,'松原市',1),
(12,'南通市',2),
(13,'镇江市',2),
(14,'金华市',3),
(15,'丽水市',3);
此时图表中:
自连接代码:
-- 自连接
select a.`name` as 省,b.`name` as 市
from pid a inner join pid b
on a.id=b.pid;
得到下图:
看代码理解即可,就是一个表当成两个表来进行连接,可以添加where,order by 语句进行更准确的筛选