gpt4 book ai didi

mysql - 使用分组计算对 MySQL 中自己 ID 的引用

转载 作者:行者123 更新时间:2023-11-29 03:05:44 26 4
gpt4 key购买 nike

我正在对数据库中的帖子运行查询。如果帖子是对另一篇帖子的回复,则它的 parent_id 大于零,否则为零。

为了生成帖子报告,我在我的 SELECT 中使用了以下内容,然后按用户分组。

SELECT
SUM(IF(parent_id = 0, 1, 0)) as 'NewPosts',
SUM(IF(parent_id > 0, 1,0)) as 'Responses',
COUNT(parent_id) as 'TotalPosts',
FROM posts
GROUP BY user

现在我需要添加一个列来显示用户的 self 回复。像...

SUM(IF(parent_id IN id, 1, 0)) as 'SelfResponses'

当然我知道这是错误的,但我希望它能传达这个想法。

编辑:数据看起来像:

User        Id        parent_id
Henry 12 0
Henry 24 12
Henry 32 16
Joseph 16 0

所以在这种情况下输出将是:

User         NewPosts        Responses     TotalPosts        SelfResponses
Henry 2 2 3 1
Joseph 1 0 1 0

最佳答案

假设响应的 parentId 是响应的 postId 那么你可以通过以下方式实现这一点

查询 1:

SELECT
a.user,
SUM(IF(a.parent_id = 0, 1, 0)) as 'NewPosts',
SUM(IF(a.parent_id > 0, 1,0)) as 'Responses',
COUNT(a.parent_id) as 'TotalPosts',
SUM(IF(a.user = b.user, 1, 0)) as 'SelfResponses'
FROM
Table1 a
LEFT JOIN
Table1 b
ON
a.parent_id = b.id
GROUP BY
a.user

结果:

|   USER | NEWPOSTS | RESPONSES | TOTALPOSTS | SELFRESPONSES |
--------------------------------------------------------------
| Henry | 1 | 2 | 3 | 1 |
| Joseph | 1 | 0 | 1 | 0 |

SQL FIDDLE

希望对你有帮助

关于mysql - 使用分组计算对 MySQL 中自己 ID 的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15758509/

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