mysql自引用表返回父级的id和子级的数量
我有一个自引用表,我想要一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
像这样简单的事情应该有效:
Something as simple as this should work:
感谢 Dave Morris 和 Tomgrohl 提供的答案,我得以让它发挥作用。这是我使用的MySQL。
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 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;