gpt4 book ai didi

MySQL查询评论文章数以及文章详情

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

我有三个表,用户、文章和评论,如下:

用户:

id | username

文章:

id | user_id | title | content | time

评论:

id | article_id | content | time

user_idUsers 中文章作者的用户 ID; article_idArticles中评论文章的id。

现在我想列出文章,显示作者的用户名标题内容时间评论数量username 来自 Usersnumber of comments 应该来自 Comments 通过计数,其余字段是来自文章

如何在单个语句中编写查询?

我试过了

SELECT a.*, count(c.id) AS NUM_COMMENTS, u.username
FROM Commetns c
JOIN Users u
INNER JOIN Articles a
WHERE a.id = c.article_id AND u.id=a.user_id
GROUP BY a.id

但这只会返回带有评论的文章。我希望还列出没有评论的文章。

最佳答案

您需要左连接才能获取没有评论的文章

select 
a.*,
count(c.id) AS NUM_COMMENTS,
u.username
from Articles a
JOIN Users u on u.id=a.user_id
left join Commetns c on c.article_id = a.id
GROUP BY a.id

关于MySQL查询评论文章数以及文章详情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27200537/

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