Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MySQL左联接2个表按计数排序_Mysql - Fatal编程技术网

MySQL左联接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 |

我有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 | 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 |

“需要分组依据”和“投票”应为嵌套查询结果的名称