目前我有以下数据库:
表 1:Customer_Stores
unique_id
page_address
date_added
guide_summary
user_name
cover_photo
guide_title
表 2:Customer_Stories_Likes
story_id
likex
第二个表中的“喜欢”列包含 1 或 0 来指示用户是否喜欢某个帖子。
我想要做的是将这两个表与“post_id
”连接在一起,并根据 post_id
计算所有帖子的所有“喜欢”和按每个帖子获得的点赞数排序。这可以通过一条语句实现吗?或者最好使用 Count(*)
首先确定每个帖子有多少个赞?
最佳答案
是的,这是可能的,但您不需要内部联接,因为您实际上不需要 posts 表来执行此操作。
SELECT post_id, count(like) AS post_likes
FROM likes
WHERE like = 1
GROUP BY post_id
ORDER BY post_likes DESC
如果您还需要 posts 表中的其他信息,您可以将其连接到获取点赞计数的子查询。
SELECT posts.*, like_count
FROM
posts LEFT JOIN
(SELECT post_id, count(like) AS like_count
FROM likes
WHERE like = 1
GROUP BY post_id) AS post_likes
ON posts.post_id = post_likes.post_id
ORDER BY like_count DESC
我使用了 LEFT JOIN
而不是 INNER JOIN
,如果您不想包含没有点赞的帖子,可以使用 INNER JOIN
.
关于mysql - 可以在内连接中使用 Count(*) 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41883550/