MySQL将子查询转换为连接

时间:2018-03-21 17:34:23

标签: mysql

是否可以将此子查询转换为加入?

SELECT  `news`.`newsId`,
        (SELECT `comments`.`text` 
         FROM   `comments`   
         WHERE `comments`.`newsId` = `news`.`newsId` 
         order by `comments`.`date` desc 
         limit 1)   
FROM     `news` , `comments` 
where    `news`.`newsId` = `comments`.`newsId`   
GROUP BY `news`.`newsId` 
order by news.date desc;

2 个答案:

答案 0 :(得分:0)

我认为你要做的是:

SELECT n.newsId FROM news n
INNER JOIN comments c ON c.newsId = n.newsId
ORDER BY c.date DESC, n.date
LIMIT 1

由于您没有使用任何聚合功能,因此不需要GROUP BY。您可以使用DISTINCT

创建唯一条目

答案 1 :(得分:0)

我认为newsId是唯一的。

SELECT  `news`.`newsId`,
        `comments`.`text`   
FROM     `news`
CROSS APPLY (SELECT `comments`.`text` 
             FROM   `comments`   
             WHERE `comments`.`newsId` = `news`.`newsId` 
             order by `comments`.`date` desc 
             limit 1) cm  
order by news.date desc;