mysql自引用表返回父级的id和子级的数量

发布于 2024-11-05 03:11:37 字数 446 浏览 2 评论 0原文

我有一个自引用表,我想要一个 mysql 查询,该查询将仅返回最顶层的父项(parent = 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     |
+--------+-----------+

I have a self referencing table and I want a mysql query that will return only the top most parent (parent = 0) and the number of children belonging to each of those. This is what I have so far, but I know it will not work.

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     |
+--------+-----------+

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

忆离笙 2024-11-12 03:11:37
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
)
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
)
第几種人 2024-11-12 03:11:37

像这样简单的事情应该有效:

SELECT parent_id, count( * ) cnt
FROM example
WHERE parent_id
IN (
   SELECT id
   FROM `example`
   WHERE parent_id =0
)
GROUP BY parent_id

Something as simple as this should work:

SELECT parent_id, count( * ) cnt
FROM example
WHERE parent_id
IN (
   SELECT id
   FROM `example`
   WHERE parent_id =0
)
GROUP BY parent_id
聆听风音 2024-11-12 03:11:37

感谢 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
);

Thanks to the answers provided by Dave Morris and Tomgrohl I was able to get it to work. Here is the MySQL I used.

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
);
如若梦似彩虹 2024-11-12 03:11:37

您必须在列前添加表别名

SELECT id, (SELECT COUNT(inner.id) FROM example inside where inner.parent_id =outer.id) FROM exampleouter WHEREparent_id = 0;

You'll have to prefix columns with table alias

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文