exampletable
+----+--------------------+------------------+
| id | name | parent |
+----+--------------------+------------------+
| 1 | menu1 | 0 |
| 2 | menu2 | 1 |
| 3 | menu3 | 0 |
| 4 | menu4 | 3 |
| 5 | menu5 | 0 |
| 6 | menu6 | 4 |
| 7 | menu7 | 4 |
| 8 | menu8 | 7 |
+----+--------------------+------------------+
我想在同一个表中选择没有子行。
感谢。
答案 0 :(得分:0)
create table pc
( -- parent child
id int auto_increment primary key,
name varchar(20) not null,
parent int not null
);
insert pc(name,parent) values ('menu1',0),('menu2',1),('menu3',0),('menu4',3),('menu5',0),('menu6',4),('menu7',4),('menu8',7);
Select id,name from pc where id not in (select parent from pc)
+----+-------+
| id | name |
+----+-------+
| 2 | menu2 |
| 5 | menu5 |
| 6 | menu6 |
| 8 | menu8 |
+----+-------+
答案 1 :(得分:0)
这有点乱,但它会起作用:
SELECT t3.id,t3.name,t3.parent
FROM test t3
LEFT JOIN (SELECT t1.id,t1.name,t1.parent from test t1 inner join test t2 on t1.id = t2.parent) t4 on t3.id = t4.id
WHERE t4.id IS NULL;
输出:
+----+-------+--------+
| id | name | parent |
+----+-------+--------+
| 2 | menu2 | 1 |
| 5 | menu5 | 0 |
| 6 | menu6 | 4 |
| 8 | menu8 | 7 |
+----+-------+--------+