1

Beginner here! I am trying to write a query that will select the 3 most commented on results from a "results" table the comments are stored in a seperate "comments" table.

results
 - id  
 - title    
 - body   
 - etc
 - etc

comments
 - id  
 - result_id
 - user_id
 - timestamp
 - comment

So I need to select all from results and order by the amount of matches between results.id and comments.result_id but I don't really know where to start!

Thanks a lot for the help, it's much appreciated!

Martin Hunt
  • 1,135
  • 2
  • 14
  • 23

3 Answers3

2

Not tested but you can do something like that

SELECT  r.id  ,r.title, r.body
FROM results r INNER JOIN (SELECT result_id, count(id) cnt FROM comments GROUP BY result_id) c
ON r.id = c.result_id
ORDER by c.cnt DESC
Kayser
  • 6,544
  • 19
  • 53
  • 86
1

Perhaps try something like this:

SELECT COUNT(c.id) AS comment_count FROM results r
LEFT JOIN comments c ON r.id=c.result_id
GROUP BY result_id ORDER BY comment_count DESC LIMIT 3;
James
  • 11
  • 1
1

The following should work:

SELECT r.id, COUNT(r.id) AS comment_count 
FROM results r 
INNER JOIN comments c 
ON results.id = c.result_id 
GROUP BY r.id 
ORDER BY comment_count DESC

You join the two tables where the id of the result is the same as the referenced result_id from the comments table. Then you group the rows by result_id to remove duplicates. The COUNT() function sums up the grouped rows and displays the number of them.

Then just sort the result based on the generated comment count.

You could use LEFT OUTER JOIN as well, then you would get all results that have no comments as well. If you want this or not depends on your needs.

For a description of SQL joins, check out What is the difference between "INNER JOIN" and "OUTER JOIN"?

Community
  • 1
  • 1
Per Enström
  • 902
  • 8
  • 33