兄弟们,请教个sql语句

有这么一个 posts 表#

id name parent_id
1 公告 0
2 更新说明 1
3 帮助中心 0

然后我要根据父亲 name,查询出父亲本身以及其下一级的 id。比如我想查公告和公告下一级的 id,在上面例子来说,也就是根据 name = 公告的已知条件,查出 id=1 和 id=2 这两条记录,有什么效率高点的 sql 写法吗。#

我目前想到的写法是这样的,但是我感觉这样效率好像太低了
select * from posts where parend_id = (select id from posts where name='公告' ) union (select * from posts where name='公告' )

讨论数量: 6

我猜测该表数据不大,如果是这样的话,建议你通过程序去实现分类树的构建和查找功能。把数据全部查出来就好,程序封装好查找的方法

3年前 评论

select * from (select * from posts where name =' 公告 ') as t1 union (select * from posts where parent_id = t1.id)

3年前 评论

这个很常见,我的做法是:把有效的数据全部查出来,然后在程序里面去做递归,形成树。这也是很常见的做法。希望有帮助。

一般会结合层级字段,这样可以无限层级。

3年前 评论

select *,IFNULL ((select id from posts where parent_id=a.id),0) as child_id from posts as a where name = ' 公告'

不过我也建议你用递归的方式做成树状图

3年前 评论

以 parent_id 作为条件,自己和自己连接。 select p.,c. from post p LEFT JOIN post c ON p.id = c.parent_id WHERE p.name = ' 公告'

1年前 评论