Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL left join 2 tables order by count

Tags:

mysql

I have 2 tables as below and want to have select both of them result by count(column) but doesn't work please advise.

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

I'm expecting the result from select * from review with count PID column from Likes table

My current query is

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

But it did not woking, please advise.

like image 901
Thanaporn Avatar asked Dec 27 '22 17:12

Thanaporn


2 Answers

Since you are after on reviews with votes only, you can make your query shorter(and perhaps faster) by converting LEFT JOIN to INNER JOIN, and eliminating detection of COUNT: http://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

Output:

|  ID |  RID | NAME |      COMMENT | VOTES |
--------------------------------------------
| 555 | 3000 | John | John comment |     3 |
| 555 | 3001 |  Ben |  Ben comment |     1 |
like image 86
Michael Buen Avatar answered Jan 08 '23 23:01

Michael Buen


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

like image 40
guido Avatar answered Jan 08 '23 22:01

guido