开发者

SQL - get the article title with the last comment date

开发者 https://www.devze.com 2022-12-31 23:43 出处:网络
I have articles table, article_comments. I want to get the value: last_modified_all of article. I need this value to be the great date of this two:

I have articles table, article_comments.

I want to get the value: last_modified_all of article. I need this value to be the great date of this two:

    开发者_JAVA技巧
  1. the last_modified field of articles table.
  2. the last comment of article_comments last_modified column.

Can someone help me? the structure is very simple, and you can guess is without problem.


This is the greatest-n-per-group problem that comes up frequently on Stack Overflow. Here's how I solve it:

SELECT a.article_id, a.last_modified, c1.last_modified AS last_comment_date
FROM articles AS a
JOIN article_comments AS c1
 ON (a.article_id = c2.article_id)
LEFT OUTER JOIN article_comments AS c2
 ON (a.article_id = c2.article_id AND c1.last_modified < c2.last_modified)
WHERE c2.article_id IS NULL;

This has a chance of producing more than one row per article unless article_comments.last_modified is unique. To resolve this, use a tiebreaker. For instance, if there's an auto-incrementing primary key column:

SELECT a.article_id, a.last_modified, c1.last_modified AS last_comment_date
FROM articles AS a
JOIN article_comments AS c1
 ON (a.article_id = c2.article_id)
LEFT OUTER JOIN article_comments AS c2
 ON (a.article_id = c2.article_id AND (c1.last_modified < c2.last_modified
     OR c1.last_modified = c2.last_modified AND c1.comment_id < c2.comment_id))
WHERE c2.article_id IS NULL;
0

精彩评论

暂无评论...
验证码 换一张
取 消