所以我有这个查询:

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


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

结果如下

mysql - LEFT JOIN一些值返回为NULL-LMLPHP

最佳答案

您想要有关十大最新新闻的最新评论吗?

您可以使用排名功能(如果您使用的是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;

关于mysql - LEFT JOIN一些值返回为NULL,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52898405/

10-13 03:19