1

我有一个自引用表,我想要一个 mysql 查询,它只返回最顶层的父级(父级 = 0)和属于每个父级的子级数。这是我到目前为止所拥有的,但我知道它不会起作用。

SELECT id, (SELECT COUNT(id) FROM example where parent_id = id) FROM example WHERE parent_id = 0;

+--------+-----------+
|   id   | parent_id |
+--------+-----------+
|    1   |     0     |
|    2   |     1     |
|    3   |     1     |
|    4   |     0     |
|    5   |     4     |
+--------+-----------+
4

4 回答 4

2
SELECT parent_id parent, count( * ) num_children
FROM example
GROUP BY parent_id
HAVING parent_id
IN (

SELECT id
FROM `example`
WHERE parent_id =0
)
于 2011-05-03T13:32:55.937 回答
0

像这样简单的东西应该可以工作:

SELECT parent_id, count( * ) cnt
FROM example
WHERE parent_id
IN (
   SELECT id
   FROM `example`
   WHERE parent_id =0
)
GROUP BY parent_id
于 2011-05-03T13:30:21.833 回答
0

感谢 Dave Morris 和 Tomgrohl 提供的答案,我能够让它工作。这是我使用的 MySQL。

SELECT parent_id parent, count( * ) num_children
FROM example
GROUP BY parent_id
HAVING parent_id <> 0
IN (
    SELECT id
    FROM `example`
    WHERE parent_id = 0
);
于 2011-05-03T16:48:31.780 回答
-1

您必须在列前加上表别名

SELECT id, (SELECT COUNT(inner.id) FROM example inner where inner.parent_id = outer.id) FROM example external WHERE parent_id = 0;

于 2011-05-03T13:23:56.440 回答