ORDER BY date and time BEFORE GROUP BY name in mysql(ORDER BY 日期和时间 BEFORE GROUP BY 在 mysql 中的名称)
问题描述
我有一张这样的桌子:
name date time
tom | 2011-07-04 | 01:09:52
tom | 2011-07-04 | 01:09:52
mad | 2011-07-04 | 02:10:53
mad | 2009-06-03 | 00:01:01
我想要最老的名字:
SELECT *
ORDER BY date ASC, time ASC
GROUP BY name
(->不起作用!)
现在它应该先让我生气(有更早的日期)然后是汤姆
now it should give me first mad(has earlier date) then tom
但是使用 GROUP BY name ORDER BY date ASC, time ASC 会先给我更新的 mad,因为它在排序之前先分组!
but with GROUP BY name ORDER BY date ASC, time ASC gives me the newer mad first because it groups before it sorts!
再次:问题是我不能在分组之前按日期和时间排序,因为 GROUP BY 必须在 ORDER BY 之前!
again: the problem is that i can't sort by date and time before i group because GROUP BY must be before ORDER BY!
推荐答案
另一种方法:
SELECT *
FROM (
SELECT * FROM table_name
ORDER BY date ASC, time ASC
) AS sub
GROUP BY name
GROUP BY 对它命中的第一个匹配结果进行分组.如果第一个匹配的匹配恰好是您想要的匹配,那么一切都应该按预期进行.
GROUP BY groups on the first matching result it hits. If that first matching hit happens to be the one you want then everything should work as expected.
我更喜欢这种方法,因为子查询具有逻辑意义,而不是用其他条件填充它.
I prefer this method as the subquery makes logical sense rather than peppering it with other conditions.
这篇关于ORDER BY 日期和时间 BEFORE GROUP BY 在 mysql 中的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:ORDER BY 日期和时间 BEFORE GROUP BY 在 mysql 中的名称
基础教程推荐
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 是否可以执行按位分组功能? 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- 无法解决整理冲突 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
