Using ORDER BY and GROUP BY together(一起使用 ORDER BY 和 GROUP BY)
本文介绍了一起使用 ORDER BY 和 GROUP BY的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的表看起来像这样(而且我使用的是 MySQL):
My table looks like this (and I'm using MySQL):
m_id | v_id | timestamp
------------------------
6 | 1 | 1333635317
34 | 1 | 1333635323
34 | 1 | 1333635336
6 | 1 | 1333635343
6 | 1 | 1333635349
我的目标是对每个 m_id 取一次,并按最高时间戳排序.
My target is to take each m_id one time, and order by the highest timestamp.
结果应该是:
m_id | v_id | timestamp
------------------------
6 | 1 | 1333635349
34 | 1 | 1333635336
我写了这个查询:
SELECT * FROM table GROUP BY m_id ORDER BY timestamp DESC
但是,结果是:
m_id | v_id | timestamp
------------------------
34 | 1 | 1333635323
6 | 1 | 1333635317
我认为这是因为它首先执行 GROUP_BY 然后对结果进行排序.
I think it causes because it first does GROUP_BY and then ORDER the results.
有什么想法吗?谢谢.
推荐答案
一种正确使用 group by 的方法:
One way to do this that correctly uses group by:
select l.*
from table l
inner join (
select
m_id, max(timestamp) as latest
from table
group by m_id
) r
on l.timestamp = r.latest and l.m_id = r.m_id
order by timestamp desc
这是如何工作的:
- 为子查询中每个不同的
m_id选择最新的时间戳 - 仅从
table中选择与子查询中的行匹配的行(此操作 - 执行连接,但未从第二个表中选择列,它仅用作过滤器 -- 被称为 semijoin" 以防你好奇) - 对行进行排序
- selects the latest timestamp for each distinct
m_idin the subquery - only selects rows from
tablethat match a row from the subquery (this operation -- where a join is performed, but no columns are selected from the second table, it's just used as a filter -- is known as a "semijoin" in case you were curious) - orders the rows
这篇关于一起使用 ORDER BY 和 GROUP BY的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:一起使用 ORDER BY 和 GROUP BY
基础教程推荐
猜你喜欢
- 从字符串 TSQL 中获取数字 2021-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- 带更新的 sqlite CTE 2022-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
