mysql - 单表子查询

标签 mysql sql subquery hierarchical-data

好的,我有一张 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/

相关文章:

mysql - 如何在 codeigniter 中编写左连接查询?

SQL - 子查询和外表之间的关系

MySQL 中 select 的子查询

mysql - Doctrine DBAL 查询构建器连接和 where 子句

sql - 如何根据 ComosDb 中聚合函数的结果对查询结果进行排序?

mysql - 使用 SELECT 值更新 SQL 列

php - 如何在 laravel 中使用 sql NOW( ) 函数

sql - 如何从子查询返回两个字段

按特定字段分组和计数记录的Mysql子查询

php - 在 Laravel 5.2 中同时连接到多个数据库