LEFT JOIN一些值返回为NULL

时间:2018-10-19 18:55:34

标签: mysql sql

所以我有这个查询:

SELECT 
 n.newsId newsId, n.date newsDate, n.text newsText, c.date commentDate, c.text 
 commentText 
FROM 
 (SELECT * FROM news ORDER BY date DESC LIMIT 10) n 
LEFT JOIN 
 (SELECT comments.* FROM comments, news WHERE comments.newsId = news.newsId ORDER BY comments.date DESC LIMIT 1) c 
ON 
 n.newsId=c.newsId

结果大部分都可以,但是出于某些原因有一些空值。 请看看,谢谢:)

以下结果

results

1 个答案:

答案 0 :(得分:2)

您想要最新的10条最新新闻评论吗?

您可以使用排名功能(如果您使用的是mysql 8)或变量来执行此操作。

Rank function in MySQL

http://www.mysqltutorial.org/mysql-window-functions/mysql-rank-function/

尝试一下(未试用):

select newsId, newsDate, newsText, commentDate, commentText from (
    SELECT news.newsId, news.date newsDate, news.text newsText, comments.text commentText, comments.date commentDate, 
            @curRank := case when news.newsId = @curNewsId then @curRank + 1 else 1 end rnk,
            @curNewsId := news.newsId
    FROM news
    inner join comments on news.newsId = comments.newsId,
    (select @curNewsId := 0, @curRank := 0) tmp
    ORDER BY news.date DESC, comments.date desc
) sub 
where rnk = 1
order by newsDate desc
LIMIT 10;