当我一开始试图理解问题和答案时,我感到很困惑。我花了一些时间阅读,我想做一个总结。
- OP的例子有点误导。起初我不明白为什么接受的答案是接受的答案。我认为OP的要求可以简单地满足
select m_id, v_id, max(timestamp) as max_time from table
group by m_id, v_id
order by max_time desc
然后我又看了一下接受的答案。而且我发现实际上OP想要表达这一点,例如:
m_id | v_id | timestamp
------------------------
6 | 1 | 11
34 | 2 | 12
34 | 3 | 13
6 | 4 | 14
6 | 5 | 15
他想仅基于( )和 ( )选择所有列。group by
m_id
order by
timestamp
那么上面的sql就不行了。如果您仍然不明白,请想象您的列数多于 m_id | v_id | timestamp
, 例如m_id | v_id | timestamp| columnA | columnB |column C| ...
. 使用group by
,您只能在结果中选择那些“分组依据”列和聚合函数。
到目前为止,您应该已经理解了公认的答案。row_number
更重要的是, MySQL 8.0 中引入了检查功能:
https://www.mysqltutorial.org/mysql-window-functions/mysql-row_number-function/
- 查找每组的前 N 行
它的作用与公认的答案相似。
- 有些答案是错误的。我的 MySQL 给了我错误。
select m_id,v_id,max(timestamp) from table group by m_id;
@abinash sahoo
SELECT m_id,v_id,MAX(TIMESTAMP) AS TIME
FROM table_name
GROUP BY m_id
@Vikas Garhwal
错误信息:
[42000][1055] Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'testdb.test_table.v_id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by