Suppose a table of posts, and a table of comments to those posts. The table ‘comments’ has a column titled ‘post_id’, which holds the id of the target of each comment, and a column titled ‘rating’, which holds the rating for each comment (thumbs up minus thumbs down).
What I need is a query that will select all the posts, together with the HIGHEST RATED comment. An ordinary join, such as the following:
SELECT * FROM posts LEFT JOIN comments ON comments.post_id = posts.id;
…would return one row for each comment. I am guessing that I need to order the table comments by rating, and then group the results by post id. But I’ve been looking for the proper syntax to do so, and couldn’t find it (and trial and error didn’t work either). Any ideas? Thanks!
This is a classic, see http://dev.mysql.com/doc/refman/5.1/en/example-maximum-column-group-row.html.