如果没有显示na,则显示帖子的最新评论

时间:2016-03-03 13:31:10

标签: mysql

我有两个表格帖子表和评论表,对于特定帖子,可能有评论或不会有。

使用以下查询语句:

SELECT id, Post, finaltable.comments FROM table-1 INNER JOIN ( SELECT comments, ticket_id FROM table-2 INNER JOIN 
( SELECT MAX(id) latest_comment_id FROM table-2 GROUP BY ticket_id) latestcomments ON table-2.id = latestcomments.latest_comment_id ) finaltable ON finaltable.ticket_id = table-1.id

这会显示包含最新评论的帖子,但如果帖子没有评论,则根本不显示帖子。仅显示包含评论的帖子。

1 个答案:

答案 0 :(得分:1)

你应该使用LEFT JOIN

SELECT id, Post,
       CASE WHEN finaltable.comments is null then 'NA' else finaltable.comments end as comments
FROM table-1
LEFT OUTER JOIN (SELECT comments, ticket_id 
                 FROM table-2
                 INNER JOIN (SELECT MAX(id) latest_comment_id
                             FROM table-2  
                             GROUP BY ticket_id) latestcomments
                  ON table-2.id = latestcomments.latest_comment_id ) finaltable
 ON finaltable.ticket_id = table-1.id