gpt4 book ai didi

mysql - 如何在mysql中获取父级同一表中的子级行

转载 作者:行者123 更新时间:2023-11-29 17:38:31 24 4
gpt4 key购买 nike

我需要你们关于如何查询此场景的建议。

我有一个表线程,字段是:

-id 
-author_id
-content_id
-parent_id
-type

以下是表线程中的行:

id   author_Id   content_id  parent_id  type
1 3 60 3
2 3 1 1 2
3 3 2 1 2
4 3 61 3
5 3 1 4 2
6 3 2 4 2
7 3 63 1
8 3 62 1

如何查询包含 child 的 parent ?提前致谢

最佳答案

如果您只想获取带有父级数据的子级列表,则 query应该有效:

SELECT t1.id, t1.author_id, t1.content_id, t1.type, IFNULL(GROUP_CONCAT(t2.id), '') as children
FROM Thread t1
LEFT JOIN Thread t2
ON t2.parent_id = t1.id
GROUP BY t1.id

输出:

id  author_id   content_id  type    children
1 3 60 3 2,3
2 3 1 2
3 3 2 2
4 3 61 3 5,6
5 3 1 2
6 3 2 2

要仅获取有 child 的 parent 的数据,请将 LEFT JOIN 更改为 JOIN:

SELECT t1.id, t1.author_id, t1.content_id, t1.type, IFNULL(GROUP_CONCAT(t2.id), '') as children
FROM Thread t1
JOIN Thread t2
ON t2.parent_id = t1.id
GROUP BY t1.id

输出:

id  author_id   content_id  type    children
1 3 60 3 2,3
4 3 61 3 5,6

关于mysql - 如何在mysql中获取父级同一表中的子级行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50126354/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com