说我有下表:
CREATE TABLE `table` (
id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
userid INT UNSIGNED NOT NULL,
reference INT,
`datetime` DATETIME
) Engine=InnoDB;
我想从表中选择,按引用分组并按DATE排序,还要按最新参考条目排序?
例如:
reference: 79
datetime: 2011-12-31 00:32:30
reference: 77
datetime: 2011-12-31 00:40:30
reference: 77
datetime: 2011-12-31 00:43:30
reference: 77
datetime: 2011-12-31 00:45:30
reference: 78
datetime: 2011-12-31 00:47:30
他们应该按照这个顺序显示:78,77(00:45 one),79
我目前将此作为我的查询:
SELECT *
FROM `table`
WHERE `userid` = '" . mysql_real_escape_string($id) . "'
GROUP BY `reference`
ORDER BY `datetime` DESC
如何让此查询生效?因此,当已经存在的引用获得另一个条目时,它会跳转到列表的顶部吗?
谢谢
答案 0 :(得分:3)
尝试
SELECT id, userid, reference, MAX(datetime) AS datetime
FROM `table` WHERE `userid` = ID
GROUP BY `reference`
ORDER BY `datetime` DESC
答案 1 :(得分:0)
您需要指定分组依据子句附近的所有列。
SELECT id, userid, reference, MAX(datetime) AS datetime
FROM `table` WHERE `userid` = ID
GROUP BY `id`, `userid`, `reference`
ORDER BY `datetime` DESC