好的,我有一张 table
Tasks
--
TaskId (unique autoinc primary)
ChildOf (Contains task ID of parent, or 0 if top tier (no parent))
我需要编写一个查询来选择 ChildOf = 0 的所有记录......简单吧?
好的,但还需要返回另一列结果,告诉每个任务有多少个 child ......
所以结果看起来像这样......
TaskID ... ChildOf ... countChildren
37 ...... 0 .... 3
42 ...... 0 .... 0
99 ...... 0 .... 1
etc....
我知道我需要的两个查询是这样的,但需要以某种方式将它们组合起来......
Select TaskId as ParentTaskId, ChildOf from Tasks where ChildOf = 0
和
Select count(TaskId) from Tasks where ChildOf = ParentTaskId
注意:只有 2 层...... parent 和 child ......没有孙子!所以希望这能让它变得不那么复杂。
非常感谢任何帮助。感谢迄今为止的所有帮助!
最佳答案
应该这样做:
SELECT TaskId as ParentTaskId, ChildOf ,
(SELECT count(t2.TaskId)
FROM Tasks t2
WHERE t2.ChildOf = t.TaskId) as CountChildren
FROM Tasks t
WHERE t.ChildOf = 0
关于mysql - 单表子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6628691/