MySQL JOIN-ing 四个表,其中两个只有计数

标签 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 |
+--------+----------+------+--------+-------------+------+--------------+-----------+

谢谢大家的帮助,我真的很感激。

最佳答案

查询按 post.id 分组。看起来 user.id 也需要包含在内。

group by user.id, post.id

关于MySQL JOIN-ing 四个表,其中两个只有计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42635407/

相关文章:

MySQL获取具有相同id的表的总和

mysql - 删除使用 JOIN 选择的结果

php - 获取每小时插入数据库的行数

mysql - 如何在 mysql 中更改列标题,例如 sum(FREQ) 到 FREQ?

mysql - 求和返回字符串,仅适用于 postgresql

php - 从 MySQL Blob 字段中选择一部分

mysql - 按两列对 MySQL 表排序

apache-spark - PySpark - 在不使用 UDF 或 join 的情况下创建多个聚合映射列

powershell - 按多列进行计数和分组

python - 使用 SQLite 进行复杂的 SQL 查询