如果已经发布或在互联网上发布,我很抱歉。我经过长时间的搜索来到这里
假设这是表格:
+----+-------+----------+---------------------+
| id | name | group_id | created_time |
+----+-------+----------+---------------------+
| 1 | foo | 1 | 2010-09-22 00:00:00 |
| 2 | rafi | 2 | 2010-09-23 00:00:00 |
| 3 | rafi1 | 2 | 2010-09-24 00:00:00 |
| 4 | rafi2 | 2 | 2010-09-25 00:00:00 |
| 5 | bar | 5 | 2010-09-26 00:00:00 |
| 6 | baz | 6 | 2010-09-27 00:00:00 |
| 7 | baz1 | 6 | 2010-09-26 00:00:00 |
| 8 | rafi3 | 2 | 2010-09-24 00:00:00 |
| 9 | baz2 | 6 | 2010-09-30 00:00:00 |
+----+-------+----------+---------------------+
我想要的是根据组ID对它们进行分组,并按created_time desc(较新的第一个)命令
但是当我说
时SELECT id,name,group_id,created_time FROM test group by group_id ORDER BY id desc;
我明白了
+----+------+----------+---------------------+
| id | name | group_id | created_time |
+----+------+----------+---------------------+
| 6 | baz | 6 | 2010-09-27 00:00:00 |
| 5 | bar | 5 | 2010-09-26 00:00:00 |
| 2 | rafi | 2 | 2010-09-23 00:00:00 |
| 1 | foo | 1 | 2010-09-22 00:00:00 |
+----+------+----------+---------------------+
我想要的是得到这样的东西
+----+------+----------+---------------------+
| id | name | group_id | created_time |
+----+------+----------+---------------------+
| 9 | baz2 | 6 | 2010-09-30 00:00:00 |
| 5 | bar | 5 | 2010-09-26 00:00:00 |
| 5 | rafi2| 2 | 2010-09-25 00:00:00 |
| 1 | foo | 1 | 2010-09-22 00:00:00 |
+----+------+----------+---------------------+
我试过了
SELECT max(date(created_time)) as foo,name,group_id FROM test group by group_id ORDER BY foo desc;
我得到了正确的日期但却无法说出正确的名称。
答案 0 :(得分:2)
该查询是否符合您的需求?
SELECT t1.id, t1.name, t1.group_id FROM Test t1
INNER JOIN
(SELECT MAX(id) as maxid FROM Test GROUP BY group_id) t2
ON t2.maxid = t1.id
ORDER BY t1.id DESC;
修改强>
如果您想按日期时间字段排序,可以稍微修改上面的查询:
SELECT t1.id, t1.name, t1.group_id, t1.created_date FROM Test t1
INNER JOIN
(SELECT MAX(created_date) as maxdate, group_id FROM Test GROUP BY group_id) t2
ON (t2.maxdate = t1.created_date AND t2.group_id = t1.group_id)
ORDER BY t1.created_date DESC;
它仍然是你在找什么?
答案 1 :(得分:1)
这个怎么样?使用子查询是一个选项 - 如果是这样,这可能会起作用!
SELECT id, name, group_id
WHERE id
IN (Select max(id) FROM test group by group_id)
ORDER BY id desc;