1

我有一个主题表,我有一个带有评论的表。

话题

ID  TOPIC 
1   Guns
2   School
3   Politics
4   War

注释

DATE       TOPIC     TEXT
5/4/2013   School    'I love school.'
5/5/2013   War       'War sucks.'
5/6/2013   Politics  'I like politics... sometimes.'
5/7/2013   Guns      'I have a few guns. Do you?'
5/8/2013   War       'Stop fighting you guys.'

我需要的是一个 MYSQL 语句来获得这个结果(按照与该主题相关的最新评论的顺序):

TOPIC
War
Guns
Politics
School

这是按有关它们的最新评论排序的主题列表。

4

3 回答 3

1

一些建议——

  1. 将 DATE 列格式更改为 MySQL 日期格式YYYY-mm-dd
  2. 使您的 TOPIC 列成为对该 TOPIC 的主题表 ID 的引用

鉴于这些更改,您可以使用此查询来完成 -

SELECT t.`TOPIC` FROM Comments c 
JOIN Topics t ON t.ID = c.`TOPIC`
GROUP BY c.`TOPIC`
ORDER BY MAX(`DATE`) DESC

你可以看到这个 SQLFiddle 例子 - http://sqlfiddle.com/#!2/02560/1

于 2013-06-26T00:23:41.870 回答
0
SELECT * FROM `table` WHERE `topic` = 'War' ORDER BY `date`
UNION
SELECT * FROM `table` WHERE `topic` = 'Guns' ORDER BY `date`
UNION
SELECT * FROM `table` WHERE `topic` = 'Politics' ORDER BY `date`
UNION
SELECT * FROM `table` WHERE `topic` = 'School' ORDER BY `date`

不是真正的效率之母,但会起作用..

于 2013-06-26T00:12:43.090 回答
0

您正在查找此查询:

SELECT t.topic FROM Comments c 
INNER JOIN Topics t ON t.topic = c.topic
GROUP BY c.topic
ORDER BY c.date DESC

我建议添加这些:

  • 根据 MYSQL 更改日期格式。
  • 使用主题 ID 代替主题作为参考。
于 2016-01-01T22:27:02.970 回答