5

我有 2 个如下表,并希望通过 count(column) 选择它们的结果,但不起作用请告知。

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

但它没有woking,请指教。

4

2 回答 2

8

由于您只通过投票进行评论,因此您可以通过转换LEFT JOININNER JOIN并消除对以下内容的检测来缩短查询(也许更快) COUNThttp ://www.sqlfiddle.com/#!2/1f920/3

SELECT r.ID, r.RID, r.Name, `Comment`, COUNT(RID) as votes 
FROM review r 
JOIN Likes l ON l.PID = r.RID
WHERE r.ID = 555 
GROUP BY r.RID 
ORDER BY votes DESC

输出:

|  ID |  RID | NAME |      COMMENT | VOTES |
--------------------------------------------
| 555 | 3000 | John | John comment |     3 |
| 555 | 3001 |  Ben |  Ben comment |     1 |
于 2012-09-15T05:29:50.717 回答
3
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

sqlfiddle

于 2012-09-15T04:51:50.897 回答