2017-03-06 42 views
1

我想加入4桌,這些都是MySQL的JOIN-ING四個表有兩個人只能用計數

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

感謝大家的幫助球員,我很感激真多。

回答

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 
1

查詢按post.id分組。它看起來像user.id也需要包含。

group by user.id, post.id 
+0

儘管如此輸出作爲我的查詢相同 – Matej