Group by 也是 order by?
Group by and also order by?
两个表:
话题
评论(有一个主题字段,所以我知道评论是在哪个主题)
我只想获取每个主题中的最新评论(日期字段中的最大值),然后以这种方式对主题进行排序。
我试过的查询:
SELECT User, Topic, Date
FROM Comments
GROUP BY Topic
ORDER BY Date DESC
试试这个,改进的答案:
SELECT `User`,
temp.`Topic`,
temp.`Date`
FROM (
SELECT `Topic`,
MAX(`Date`) `Date`
FROM `Comments`
GROUP BY `Topic`
ORDER BY MAX(`Date`) DESC
) temp
INNER JOIN `Comments`
USING (`Topic`, `Date`)
Return 如果同一主题的其他行没有更晚的日期,则为一行。
SELECT User, Topic, Date
FROM Comments c1
where not exists (select 1 from Comments c2
where c2.topic = c1.topic
and c2.date > c1.date)
order by date desc
两个表: 话题 评论(有一个主题字段,所以我知道评论是在哪个主题)
我只想获取每个主题中的最新评论(日期字段中的最大值),然后以这种方式对主题进行排序。
我试过的查询:
SELECT User, Topic, Date
FROM Comments
GROUP BY Topic
ORDER BY Date DESC
试试这个,改进的答案:
SELECT `User`,
temp.`Topic`,
temp.`Date`
FROM (
SELECT `Topic`,
MAX(`Date`) `Date`
FROM `Comments`
GROUP BY `Topic`
ORDER BY MAX(`Date`) DESC
) temp
INNER JOIN `Comments`
USING (`Topic`, `Date`)
Return 如果同一主题的其他行没有更晚的日期,则为一行。
SELECT User, Topic, Date
FROM Comments c1
where not exists (select 1 from Comments c2
where c2.topic = c1.topic
and c2.date > c1.date)
order by date desc