这个问题在这里已有答案:
我这里有一个示例数据:
这是我想要的输出:
如何根据最短时间获得明确的价值?
这是我试过的更新
用于过滤的相关子查询可能是最简单的解决方案:
select t.*
from t
where t.timestamp = (select min(t2.timestamp)
from t t2
where t2.id = t.id
);
如果您想要最早的记录,您可能需要考虑日期:
select t.*
from t
where (t.date, t.time) in (select t2.date, t2.time
from t t2
where t2.id = t.id
order by t2.date desc, t2.time desc
);
或者如果您想要每个日期的最早记录:
select t.*
from t
where t.timestamp = (select min(t2.timestamp)
from t t2
where t2.id = t.id and
t2.date = t.date
);
使用MySQL 8.0,窗口函数通常是最有效的方法:
SELECT col1, col2, col3, col4, col5
FROM (
SELECT t.*, ROW_NUMBER() OVER(PARTITION BY col2 ORDER BY col4) rn
FROM mytable t
) x WHERE rn = 1
对于早期版本,我会使用带有相关子查询的NOT EXISTS
条件:
SELECT *
FROM mytable t
WHERE NOT EXISTS (
SELECT 1 FROM mytable t1 WHERE t1.col2 = t.col2 AND t1.col4 < t.col4
)
| col1 | col2 | col3 | col4 | col5 |
| ---- | ---- | ---------- | -------- | ---------- |
| 2 | AAA | Customer 1 | 07:00:00 | 2019-03-04 |
| 3 | BBB | Customer 2 | 15:00:00 | 2019-03-04 |
为了有效地执行此操作,您需要mytable(col2, col4)
上的索引:
CREATE INDEX mytable_idx ON mytable(col2, col4);
如果您有多个具有相同col1
和col2
的记录,则可以使用列c1
添加其他条件以避免结果集中的重复,我理解这是表的主键:
SELECT *
FROM mytable t
WHERE NOT EXISTS (
SELECT 1
FROM mytable t1
WHERE
t1.col2 = t.col2
AND (
t1.col4 < t.col4
OR (t1.col4 = t.col4 AND t1.col1 < t.col1)
)
)