进行 MySQL COUNT 查询

Making a MySQL COUNT query

经过 4 天的尝试和网络研究后,我无法实现我的愿望。
任何帮助将不胜感激!
执行于 MYSQL WORKBENCH
我有一个由 3 个表组成的数据库:

user Posts likes
username id id
id title userId (foreign key from user.id)
email content postId (foreign key from posts.id)
password date
image imageUrl
userId (foreign key from user.id)

我想要一个查询,该查询将从 USER 和 POSTS 中获取特定数据,加上按 ID post 排序的每个 post 的总点赞数,如果不存在点赞,则总结果为 0有了这个ID。 这是我希望查询执行的操作的列表:

我的实际查询:

SELECT P.id, P.userId, P.title, P.content, P.date, P.imageUrl, U.username, U.permission, U.image,
COUNT(CASE WHEN L.postId = P.id THEN 1 ELSE NULL END) AS totalLikes
FROM posts AS P
LEFT JOIN user AS U
ON U.id = P.userId
LEFT JOIN likes AS L
ON P.id = L.postId
ORDER BY P.id DESC;

这只返回 1 post,其中包含数据库中所有喜欢的计数,所以不是我所期望的:-(

仅在 likes 内进行聚合,然后将其他表连接到聚合结果集:

SELECT P.id, P.userId, P.title, P.content, P.date, P.imageUrl, 
       U.username, U.permission, U.image,
       COALECE(L.totalLikes, 0) AS totalLikes
FROM posts AS P
INNER JOIN user AS U ON U.id = P.userId  -- change to LEFT JOIN if the column userId in posts is nullable
LEFT JOIN (
  SELECT postId, COUNT(*) AS totalLikes
  FROM likes 
  GROUP BY postId
) AS L ON L.postId = P.id
ORDER BY P.id DESC;