我有一个主题表,我有一个评论表。
主题
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
这是按最新评论排序的主题列表。
答案 0 :(得分:1)
一些建议 -
YYYY-mm-dd
鉴于这些更改,您可以使用此查询执行此操作 -
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
答案 1 :(得分: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`
不是真正的效率之母,但会起作用..
答案 2 :(得分: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
我建议添加以下内容: