MySQL连接两个表并限制和排序它们

时间:2017-10-18 13:55:02

标签: mysql

有一个新闻表和一个评论表。我需要从新闻表中获取10条最新的新闻帖子,并加入他们的帖子中的最新评论。

数据库结构和我到目前为止所尝试的是:

CREATE TABLE News (newsId INT AUTO_INCREMENT, text VARCHAR(1000), date DATETIME, PRIMARY KEY(newsId));
CREATE TABLE Comments (commentId INT AUTO_INCREMENT, text VARCHAR(1000), date DATE, newsId INT, PRIMARY  KEY (commentId));

INSERT INTO News (newsId, text, date) VALUES
(NULL, "1st random text", NOW()), (NULL, "2nd random text", NOW()), (NULL, "3rd NEWS text", '2017-10-10 15:30:00'),
(NULL, "4th random text", '2017-10-10 15:35:00'), (NULL, "5th random text", '2017-10-10 15:32:00'),
(NULL, "6th random text", '2017-10-10 15:34:00'), (NULL, "7th random text", '2017-10-10 15:31:00');

INSERT INTO Comments (commentId, text, date, newsId) VALUES
(NULL, "1st random comment", NOW(), 1), (NULL, "2nd random comment", '2017-10-10 15:34:00' , 1), (NULL, "3rd NEWS comment", NOW(), 2),
(NULL, "4th random comment", '2017-10-10 15:39:00', 2), (NULL, "5th random comment", '2017-10-10 23:34:00',3),
(NULL, "6th random comment", NOW(),3), (NULL, "7th random comment", NOW(),4);

SELECT N.*, C.*
FROM News N((
ORDER BY N.date DESC
LIMIT 10)
    LEFT JOIN Comments C
    ON C.newsId = N.newsId
    ORDER BY C.date DESC
    LIMIT 1);

但是这不起作用并且引发了语法错误。不知道我怎么写这个。此外,我希望在没有提问的情况下提出建议,提前谢谢。

EDIT。我得到的错误

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual 

that corresponds to your MySQL server version for the right syntax to use near '((
ORDER BY N.date DESC
LIMIT 10)
    LEFT JOIN Comments C
    ON C.newsId = N.n' at line 2

2 个答案:

答案 0 :(得分:2)

这可以解决您的问题吗?

SELECT N.*, P.*
FROM News N
LEFT JOIN (SELECT c.* FROM Comments C
           LEFT JOIN Comments c1 ON(c.newsId = c1.newsId and c1.date > c.date)
           WHERE c1.date IS NULL) p
 ON (p.newsId = N.newsId)
ORDER BY N.date DESC
LIMIT 10;

您的代码存在多个问题。首先,第一个ORDER BY子句是错误的。 Order by在查询结束时,您无法打开括号,因为优化器认为您启动了一个子查询。

其次,“我想要对每个帖子发表最新评论”,这意味着您需要最新的每个组。许多RDBMS提供像row_number()这样的窗口函数来解决这个问题。不幸的是,这是MySQL,这意味着您要么必须进行自联接(查看我的内部查询)或使用某种相关查询。

答案 1 :(得分:1)

首先,您需要获取最新的10条新闻

SELECT N.*
FROM News N
ORDER BY N.date DESC 
LIMIT 10

然后找到最新的评论。在我的情况下,如果存在比它更新的评论,我会拒绝行。

<强> SQL DEMO

SELECT *
FROM (SELECT N.*
      FROM News N
      ORDER BY N.date DESC 
      LIMIT 10) as recent_news
LEFT JOIN  Comments C1
       ON  recent_news.newsId = C1.newsId
WHERE NOT EXISTS (SELECT 1
                  FROM Comments C2
                  WHERE C2.newsId = C1.newsId
                    AND C2.date > C1.date)