MySQL加入四个表,其中两个表只有count

时间:2017-03-06 20:58:14

标签: mysql join count left-join

我想加入4个表,这些是表

+-----------------------------------------+
|                  User                   |
+----+----------+----------+-------+------+
| id | username | password | email | name |
+----+----------+----------+-------+------+

+----------------------------------+
|               Post               |
+----+--------+-------------+------+
| id | userID | description | time |
+----+--------+-------------+------+

+------------------------------------+
|               Comment              |
+----+--------+--------+------+------+
| id | userID | postID | text | time |
+----+--------+--------+------+------+

+----------------------+
|         Love         |
+----+--------+--------+
| id | userID | postID |
+----+--------+--------+

我想显示所有用户的所有帖子,其中包含评论数量和“喜欢”标记。这是我现在的查询,但它返回countComment和countLove的错误值:

SELECT User.id AS userID, User.username, User.name, Post.id AS postID, Post.description, Post.time, COUNT(Comment.id) AS countComment, COUNT(Love.id) as countLove
FROM User
    JOIN Post ON User.id = Post.userID
    LEFT JOIN Comment ON Comment.postID = Post.id
    LEFT JOIN Love ON Love.postID = Post.id
GROUP BY Post.id
ORDER BY User.id ASC, Post.time DESC

我想看到的字段:

+--------+----------+------+--------+-------------+------+--------------+-----------+
| userID | username | name | postID | description | time | countComment | countLove |
+--------+----------+------+--------+-------------+------+--------------+-----------+

谢谢大家的帮助,我非常感激。

2 个答案:

答案 0 :(得分:1)

查询按post.id进行分组。看起来像user.id也需要包括在内。

group by user.id, post.id

答案 1 :(得分:0)

我设法使用此查询做了我想要的事情:

SELECT
    User.id AS userID, User.username, User.name,
    Post.id AS postID, Post.description, Post.time,
    COALESCE(c.count, 0) AS countComment, COALESCE(l.count, 0) AS countLove
FROM User
    JOIN Post ON User.id = Post.userID
    LEFT JOIN (SELECT Comment.postID, COUNT(*) AS count FROM Comment GROUP BY Comment.postID) c ON c.postID = Post.id
    LEFT JOIN (SELECT Love.postID, COUNT(*) AS count FROM Love GROUP BY Love.postID) l ON l.postID = Post.id
ORDER BY User.id ASC, Post.id DESC