请教一个MySql查询语句
idparentid
10
20
30
41
52
如格式如上,
要求不太好解释,总之需要筛选出ID为4、5、3的项目。
因为ID4,5有父项目分别为ID1,2所以ID1,2不显示
而ID3无子项目,所以列出来
求SQL语句,请注意平台是mysql
[解决办法]
- SQL code
create table tb(id int,parentid int)insert into tb values(1 ,0)insert into tb values(2 ,0)insert into tb values(3 ,0)insert into tb values(4 ,1)insert into tb values(5 ,2)goselect * from tb twhere exists(select 1 from tb m where t.parentid = m.id)ornot exists(select 1 from tb n where t.id = n.parentid)drop table tb/*id parentid ----------- ----------- 3 04 15 2(所影响的行数为 3 行)*/
[解决办法]
select * from test where id not in ( select t1.id from test t1 join test t2 on t1.id = t2.parentid )