简体   繁体   English

MySQL查询,分组,然后按最近分组的顺序?

[英]mySQL Query, group by and then order by most recent grouped?

Say I have the following table: 说我有下表:

CREATE TABLE `table` (
    id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
    userid INT UNSIGNED NOT NULL,
    reference INT,
    `datetime` DATETIME
) Engine=InnoDB;

I want to select from the table, group by the reference and order by DATE, but also order by the latest reference entry? 我想从表格中进行选择,按引用分组,按DATE排序,还按最新引用条目排序?

For example: 例如:

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

They should show in this order: 78, 77 (the 00:45 one), 79 它们应按以下顺序显示:78、77(00:45一个),79

I currently have this as my query: 我目前有这个作为我的查询:

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

How can I get this query to work? 我怎样才能使该查询工作? So when a reference which already exists gets another entry, it jumps to the top of the list? 因此,当已经存在的引用获得另一个条目时,它跳到列表的顶部?

Thank you 谢谢

Try 尝试

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

you need to specify all the columns near Group By clause. 您需要在Group By子句附近指定所有列。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM