我想加入 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 |
+--------+----------+------+--------+-------------+------+--------------+-----------+
谢谢大家的帮助,我真的很感激。
最佳答案
查询按 post.id 分组。看起来 user.id 也需要包含在内。
group by user.id, post.id
关于MySQL JOIN-ing 四个表,其中两个只有计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42635407/