0

我有两个表新闻和评论:

新闻:newsId、newsTitle、newsDate、newsReadCount

评论: ID, newsID, comment, ndate

我根据两个日期之间的值 newsReadCount 选择了 10 行具有最大读取的行:

SELECT * FROM news WHERE DATE(newsDate) BETWEEN '20120414' AND '20130414' ORDER BY newsReadCount DESC LIMIT 0, 10

在这里,我想选择 10 个带有 newsTitle 的新闻,从两个日期之间的新闻表中的总评论数根据评论表的关系 newsID 具有最大评论数。我如何在mysql中查询这个?我需要加入吗。请帮助我,我是 mysql 新手。

评论表的newsID是新闻表的新闻ID主键的值。

编辑:

选择两个日期之间的新闻,结果如下

结果:

| newsTitle  | Total Comments |     
-------------------------------    
| onenews    |  25            |    
| another    |  30            |
4

2 回答 2

1

你需要join, a group by, anorder by和 a limit

SELECT
    news.newsTitle, COUNT(comments.ID) AS `Total Comments`
FROM news INNER JOIN comments ON
    news.newsId = comments.newsID AND news.newsDate BETWEEN '20120414' AND '20130414'
GROUP BY news.newsId
ORDER BY `Total Comments` DESC
LIMIT 10;

请看sql fiddle

于 2013-04-07T06:27:35.880 回答
0

我认为你可以使用

SELECT n.newsTitle, count(c.ID) as totalCount
FROM   News n LEFT JOIN Comments c ON n.newsId = c.newsID
WHERE  DATE(n.newsDate) BETWEEN '20120414' AND '20130414'
GROUP BY n.newsTitle
ORDER BY totalCount DESC
LIMIT   10
于 2013-04-07T06:31:22.077 回答