gpt4 book ai didi

mysql - SQL (MySQL) 同时连接、求和和计数

转载 作者:行者123 更新时间:2023-11-29 02:21:07 25 4
gpt4 key购买 nike

我需要一个包含 posts-id、posts-title、posts-created_at、users-name、number-of-comments 和 likes-status 的查询。如果不存在,喜欢状态为 0。像这样:

id |title   |created_at |name  |status  |commentscount |
========================================================
1 |Hello 1 |2015-07-22 |Baker |-2 |2 |
2 |Hallo 2 |2015-07-23 |Tom |0 |0 |

我的尝试:

SELECT p.id, p.title, p.created_at, u.name, COALESCE(c.body, 0) as commentscount, COALESCE(sum(l.status), 0) as status
FROM posts p
LEFT OUTER JOIN likes l ON l.post_id = p.id
LEFT OUTER JOIN users u ON u.id = p.user_id
LEFT OUTER JOIN comments c ON c.post_id = p.id
GROUP BY p.id, p.title, p.created_at, u.name, c.body

结果:id 1 应被汇总,commentscount 应为 2。Status -2 应保持不变。

id |title   |created_at |name  |status  |commentscount |
========================================================
1 |Hello 1 |2015-07-22 |Baker |-2 |Comment 1 | << issue
1 |Hello 1 |2015-07-22 |Baker |-2 |Comment 2 | << issue
2 |Hallo 2 |2015-07-23 |Tom |0 |0

用户表

id |name  |email             |password |created_at |
====================================================
1 |Baker |baker@example.com |UHds(& |2015-07-20 |
2 |Tom |tom@example.com |ihj=)? |2015-07-21 |

帖子表

id |user_id |title   |created_at |
==================================
1 |1 |Hello 1 |2015-07-22 |
2 |2 |Hello 2 |2015-07-23 |

喜欢表

id |user_id |post_id |status |created_at  |
===========================================
1 |1 |1 |-1 |2015-07-24 |
2 |2 |1 |-1 |2015-07-25 |

评论表

id |user_id |post_id |body      |created_at  |
==============================================
1 |1 |1 |Comment 1 |2015-07-28 |
2 |2 |1 |Comment 2 |2015-07-28 |

另请参阅:SQL join, sum, group-by and instead of null 0

最佳答案

您可以仅使用所需的计数加入子查询。这将加快您的查询速度并消除在外部子句中使用 GROUP BY 的需要:

SELECT p.id, p.title, p.created_at, u.name, COALESCE(c.comments_count, 0) AS comments_count, COALESCE(l.status_sum, 0) AS status_sum 
FROM posts p
LEFT OUTER JOIN users u ON u.id = p.user_id
LEFT OUTER JOIN (
SELECT l.post_id, SUM(l.status) AS status_sum
FROM likes l
GROUP BY l.post_id
) l ON l.post_id = p.id
LEFT OUTER JOIN (
SELECT c.post_id, COUNT(*) as comments_count
FROM comments c
GROUP BY c.post_id
) c ON c.post_id = p.id

关于mysql - SQL (MySQL) 同时连接、求和和计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31664287/

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