gpt4 book ai didi

mysql - 同时从另一个表中选择数据和计数

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

我只想回应文章并按用户评论的最多数量排序。这是我的两张 table

tbl_文章

article_id  |  articles_title  |
1 | This is 1st |
2 | This 2nd |

评论:

comment_id  |   user_id     | article_id | comment_msg
1 | 1 | 1 | my comment1
2 | 1 | 2 | my comment2
3 | 2 | 1 | some comment1

如何连接这些表并强制产生这样的结果

 article_id|articles_title|  comment_count  |
1 | This is 1st | 2 |
2 | This 2nd | 1 |

谢谢

最佳答案

下面的查询使用 INNER JOIN,它只会在结果中显示至少有 1 条评论的所有文章。如果你想在没有评论的情况下显示文章,将 INNER JOIN 更改为 LEFT JOIN

SELECT  a.article_ID,
a.article_title,
COUNT(*) Comment_Count
FROM articles a
INNER JOIN comment b
ON a.article_ID = b.article_ID
GROUP BY a.article_ID, a.article_title

要进一步了解有关联接的更多信息,请访问以下链接:

关于mysql - 同时从另一个表中选择数据和计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16182046/

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