som*_*ser 10 mysql tree hierarchy
我想使用 MySQL 在一个查询中执行以下操作:
如何在一个查询中完成此操作?如果您需要更多信息,请告诉我,我很乐意为您提供帮助。我不是创建问题的专家,所以请告诉我您需要什么更多信息。
这是我现在正在做的一个例子:
select id from messages where parent_id=0
Run Code Online (Sandbox Code Playgroud)
进而
select count(id) from messages where parent_id={{previously_chosen_id}}
Run Code Online (Sandbox Code Playgroud)
如何获得一次性查询?就像是...
select id, count(records where parent_id=the id we just asked for)
Run Code Online (Sandbox Code Playgroud)
或者,有没有更好的方法来处理这个问题?你看,目前我必须运行大量查询才能找到计数,而我宁愿一次性完成。
这可以通过内嵌子查询轻松实现:
select m.id,
(select count(*) from messages where parent_id= m.id ) as ChildCount
from messages m
where m.parent_id = 0
Run Code Online (Sandbox Code Playgroud)
请注意,group by不需要因为使用了子查询。
| 归档时间: |
|
| 查看次数: |
25465 次 |
| 最近记录: |