MySQL左联接2个表按计数排序
我有2个表如下,并希望有选择他们两个结果计数(列),但不工作,请通知MySQL左联接2个表按计数排序,mysql,Mysql,我有2个表如下,并希望有选择他们两个结果计数(列),但不工作,请通知 review table ID | RID | Name | comment 555|3000 | John | John comment 555|3001 | Ben | Ben comment 555|3002 | Smith| Smith comment Likes table U | PID 1 | 3000 2 | 3000 3 | 3000 4 | 3001 Expected result ID |
review table
ID | RID | Name | comment
555|3000 | John | John comment
555|3001 | Ben | Ben comment
555|3002 | Smith| Smith comment
Likes table
U | PID
1 | 3000
2 | 3000
3 | 3000
4 | 3001
Expected result
ID | RID | Name | comment | votes
555|3000 | John | John comment | 3
555|3001 | Ben | Ben comment | 1
SELECT ID, RID, Name, `Comment`, COUNT(RID) as votes
FROM review AS there
LEFT JOIN Likes b ON there.RID = b.PID
WHERE ID = 555
AND there.RID = b.PID
GROUP BY b.PID
HAVING votes > 0
ORDER BY votes DESC
我期待着来自select*from review和Likes表中的count PID列的结果
我现在的问题是
SELECT * , (SELECT COUNT( PID ) FROM Likes AS votes WHERE there.ID = PID)
FROM review AS there
LEFT JOIN Likes b ON there.RID = b.PID
WHERE ID =555
AND there.RID = b.PID AND votes>0
ORDER BY votes DESC
但它没有起作用,请告知
review table
ID | RID | Name | comment
555|3000 | John | John comment
555|3001 | Ben | Ben comment
555|3002 | Smith| Smith comment
Likes table
U | PID
1 | 3000
2 | 3000
3 | 3000
4 | 3001
Expected result
ID | RID | Name | comment | votes
555|3000 | John | John comment | 3
555|3001 | Ben | Ben comment | 1
SELECT ID, RID, Name, `Comment`, COUNT(RID) as votes
FROM review AS there
LEFT JOIN Likes b ON there.RID = b.PID
WHERE ID = 555
AND there.RID = b.PID
GROUP BY b.PID
HAVING votes > 0
ORDER BY votes DESC
由于您只关注有投票权的评论,您可以通过将
左连接
转换为内部连接
,并消除对计数的检测,从而缩短查询时间(可能更快):
输出:
| ID | RID | NAME | COMMENT | VOTES |
--------------------------------------------
| 555 | 3000 | John | John comment | 3 |
| 555 | 3001 | Ben | Ben comment | 1 |
“需要分组依据”和“投票”应为嵌套查询结果的名称