2012-01-01 101 views
0

说我有如下表:mySQL查询,按最近分组顺序排序?

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(在○点45分之一),79

我现在有这是我的查询:

SELECT * 
    FROM `table` 
    WHERE `userid` = '" . mysql_real_escape_string($id) . "' 
    GROUP BY `reference` 
    ORDER BY `datetime` DESC 

我怎样才能使这个查询工作?所以当已经存在的引用获得另一个条目时,它会跳转到列表的顶部?

谢谢

+0

该mysql扩展已过时,并在其弃用的方式。新代码应该使用mysqli或PDO,它们都具有重要的优点,例如支持预处理语句。 – outis 2012-01-01 12:45:14

+2

可能的重复[在MySQL中选择GROUP BY的最新行](http://stackoverflow.com/questions/5688063/),[查询最近的条目与扭曲](http://stackoverflow.com/questions/4125515 /),[MySQL查询,MAX()+ GROUP BY](http://stackoverflow.com/questions/5657446/),... – outis 2012-01-01 12:59:56

回答

3

尝试

SELECT id, userid, reference, MAX(datetime) AS datetime 
FROM `table` WHERE `userid` = ID 
GROUP BY `reference` 
ORDER BY `datetime` DESC 
+0

完美,谢谢! – Latox 2012-01-01 12:48:07

0

需要近集团指定的所有列通过条款。

SELECT id, userid, reference, MAX(datetime) AS datetime 
FROM `table` WHERE `userid` = ID 
GROUP BY `id`, `userid`, `reference` 
ORDER BY `datetime` DESC 
+0

@johntotetwoo不在mySQL你不[看这里](http://dev.mysql.com/doc/refman/5.0/en/group-by-hidden-columns.html) – xQbert 2012-01-01 13:00:45

+0

有没有必要做这是因为查询仅针对一个用户的行('WHERE userid = ID') – piotrekkr 2012-01-01 13:01:10