Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TSQL left join and only last row from right

I'm writing sql query to get post and only last comment of this post(if exists). But I can't find a way to limit only 1 row for right column in left join.

Here is sample of this query.

SELECT post.id, post.title,comment.id,comment.message from post left outer join comment on post.id=comment.post_id 

If post has 3 comments I get 3 rows with this post, but I want only 1 row with last comment(ordered by date).

Can somebody help me with this query?

like image 359
barbarian Avatar asked Feb 17 '10 14:02

barbarian


People also ask

IS LEFT join same as right join if the order of the table is reversed?

If there are only two tables, then yes.

Does LEFT join return all rows?

The SQL LEFT JOIN returns all rows from the left table, even if there are no matches in the right table. This means that if the ON clause matches 0 (zero) records in the right table; the join will still return a row in the result, but with NULL in each column from the right table.

Can we use left and right join in same query?

The only you can do that is by using UNION .


2 Answers

SELECT  post.id, post.title, comment.id, comment.message FROM    post OUTER APPLY         (         SELECT  TOP 1 *         FROM    comment с         WHERE   c.post_id = post.id         ORDER BY                 date DESC         ) comment 

or

SELECT  * FROM    (         SELECT  post.id, post.title, comment.id, comment.message,                 ROW_NUMBER() OVER (PARTITION BY post.id ORDER BY comment.date DESC) AS rn         FROM    post         LEFT JOIN                 comment         ON      comment.post_id = post.id         ) q WHERE   rn = 1 

The former is more efficient for few posts with many comments in each; the latter is more efficient for many posts with few comments in each.

like image 181
Quassnoi Avatar answered Oct 05 '22 16:10

Quassnoi


Subquery:

SELECT p.id, p.title, c.id, c.message FROM post p LEFT join comment c ON c.post_id = p.id AND c.id =                   (SELECT MAX(c.id) FROM comment c2 WHERE c2.post_id = p.id) 
like image 41
AGoodDisplayName Avatar answered Oct 05 '22 17:10

AGoodDisplayName