请教一个MySql查询语句

shaoming01 2012-02-26 12:01:55
id parentid
1 0
2 0
3 0
4 1
5 2
如格式如上,
要求不太好解释,总之需要筛选出ID为4、5、3的项目。
因为ID4,5有父项目分别为ID1,2所以ID1,2不显示
而ID3无子项目,所以列出来

求SQL语句,请注意平台是mysql
...全文
59 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
shaoming01 2012-02-26
  • 打赏
  • 举报
回复
测试有效,结帖给分,谢谢!!!!!!
Rebecca粑粑 2012-02-26
  • 打赏
  • 举报
回复
select * from test where id not in ( select t1.id from test t1 join test t2 on t1.id = t2.parentid )
dawugui 2012-02-26
  • 打赏
  • 举报
回复
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)
go

select t.* from tb t
where exists(select 1 from tb m where t.parentid = m.id)
or
not exists(select 1 from tb n where t.id = n.parentid)

drop table tb

/*
id parentid
----------- -----------
3 0
4 1
5 2

(所影响的行数为 3 行)
*/
dawugui 2012-02-26
  • 打赏
  • 举报
回复

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)
go

select * from tb t
where exists(select 1 from tb m where t.parentid = m.id)
or
not exists(select 1 from tb n where t.id = n.parentid)

drop table tb

/*
id parentid
----------- -----------
3 0
4 1
5 2

(所影响的行数为 3 行)
*/
shaoming01 2012-02-26
  • 打赏
  • 举报
回复
没找到mssql板块,不过mysql跟mssql语句基本不都通用的吗?
叶子 2012-02-26
  • 打赏
  • 举报
回复
这里是MSSQL 板块呀,建议转到MYSQL板块。

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧