我有两个简单的SELECT查询 - 加入MySQL DB中的同一个表:
SELECT uID, externaluID, COUNT(editID) AS editCount
FROM users
LEFT JOIN (edits
INNER JOIN posts
ON postRefID = postID AND editAuthorID <> authorID AND isa = 0)
ON editAuthorID = uID
GROUP BY uID
ORDER BY uID;
SELECT uID, externaluID, COUNT(posts.postID) AS postCount, SUM(value)
FROM users
LEFT JOIN (posts
LEFT JOIN usrR ON posts.postID = usrR.postID)
ON authorID = uID
GROUP BY authorID
ORDER BY uID;
到目前为止一切顺利。现在我想合并这些查询。我的方法是
SELECT uID, externaluID, COUNT(editID) AS editCount, COUNT(P2.postID) AS postCount, SUM(rateValue)
FROM users
LEFT JOIN (edits
INNER JOIN posts AS P1
ON postRefID = P1.postID AND editAuthorID <> P1.authorID AND isa = 0)
ON editAuthorID = uID
LEFT JOIN (posts AS P2
LEFT JOIN usrR ON P2.postID = usrR.postID)
ON P2.authorID = uID
GROUP BY P2.authorID, uID
ORDER BY uID;
但它返回错误的结果。我做错了什么?
答案 0 :(得分:1)
试试这个:
SELECT u1.uID, u1.externaluID, COUNT(e1.editID) AS editCount, u2.postCount, u2.sumValue
FROM users u1
LEFT JOIN (edits INNER JOIN posts
ON postRefID = postID AND editAuthorID <> authorID AND isa = 0) as e1
ON e1.editAuthorID = u1.uID
LEFT JOIN (
SELECT uID, externaluID, COUNT(posts.postID) AS postCount, SUM(value) as sumValue
FROM users
LEFT JOIN (posts
LEFT JOIN usrR ON posts.postID = usrR.postID)
ON authorID = uID
GROUP BY authorID
ORDER BY uID) as u2 on u1.uID = u2.uID
GROUP BY u1.uID,u2.postCount, u2.sumValue
ORDER BY u1.uID