单表上的子查询

时间:2011-07-08 18:21:49

标签: mysql sql subquery hierarchical-data

好的,我有一张桌子

Tasks
--
TaskId  (unique autoinc primary)
ChildOf   (Contains task ID of parent, or 0 if top tier (no parent))

我需要编写一个查询,选择ChildOf = 0的所有记录......简单吧?

好的但是还需要返回另一个列,其结果告诉每个任务有多少个孩子......

所以结果看起来像这样......

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层......父母和孩子......没有孙子!所以希望这会使它变得不那么复杂。

非常感谢任何帮助。感谢目前为止的所有帮助!

2 个答案:

答案 0 :(得分:2)

这样的事情应该这样做:

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

答案 1 :(得分:0)

试试这个:

SELECT T1.TaskID, T1.ChildOf, count(*) from 
  Tasks as T1 join Tasks as T2 on T1.TaskID = T2.ChildOf 
  WHERE T1.ChildOf = 0 
    GROUP BY (T1.TaskID)