如何从 mysql table 的重复记录中检索最新数据
how to retrieve latest data from mysql table out of duplicate records
我正在尝试从我的 sql table 中检索每条记录的最新数据。每条记录都会有一些数据变化的重复数据。我需要检索最新的时间戳数据。有人可以建议哪个是性能方面的最佳解决方案。已经看到一些带有内部连接和子查询的解决方案。
下面给出的示例数据
Technology Students Amount Area Date
python 500 1000 Bangalore 2021-08-06 12:03:26
Ruby 100 1000 Bangalore 2021-08-06 05:18:50
Java 300 1000 Bangalore 2021-08-06 18:23:40
python 900 1000 Bangalore 2021-08-06 16:23:30
Java 100 1000 Bangalore 2021-08-06 12:23:50
Ruby 500 1000 Bangalore 2021-08-06 15:13:40
我的 o/p 应该包含每个技术的最新数据
Technology Students Amount Area Date
Java 300 1000 Bangalore 2021-08-06 18:23:40
python 900 1000 Bangalore 2021-08-06 16:23:30
Ruby 500 1000 Bangalore 2021-08-06 15:13:40
一种方法:-
*将 Table 替换为真正的 table 名称。
select table.*
from table
join
(
select Technology, max(Date) as max_dt
from table
group by Technology
) t
on table.Technology= t.Technology and table.Date = t.max_dt
不需要自连接的最高效解决方案是使用 window function
,可选地使用 cte
,尽管子查询也可以。
不幸的是,row_number()
仅从 8.0 版开始受支持,但是为了完整起见并在此处包含以说明您应该升级的原因!
with latest as (
select * , Row_Number() over(partition by technology order by date desc) rn
from t
)
select Technology, Students, Amount, Area, Date
from latest
where rn=1
我正在尝试从我的 sql table 中检索每条记录的最新数据。每条记录都会有一些数据变化的重复数据。我需要检索最新的时间戳数据。有人可以建议哪个是性能方面的最佳解决方案。已经看到一些带有内部连接和子查询的解决方案。
下面给出的示例数据
Technology Students Amount Area Date
python 500 1000 Bangalore 2021-08-06 12:03:26
Ruby 100 1000 Bangalore 2021-08-06 05:18:50
Java 300 1000 Bangalore 2021-08-06 18:23:40
python 900 1000 Bangalore 2021-08-06 16:23:30
Java 100 1000 Bangalore 2021-08-06 12:23:50
Ruby 500 1000 Bangalore 2021-08-06 15:13:40
我的 o/p 应该包含每个技术的最新数据
Technology Students Amount Area Date
Java 300 1000 Bangalore 2021-08-06 18:23:40
python 900 1000 Bangalore 2021-08-06 16:23:30
Ruby 500 1000 Bangalore 2021-08-06 15:13:40
一种方法:- *将 Table 替换为真正的 table 名称。
select table.*
from table
join
(
select Technology, max(Date) as max_dt
from table
group by Technology
) t
on table.Technology= t.Technology and table.Date = t.max_dt
不需要自连接的最高效解决方案是使用 window function
,可选地使用 cte
,尽管子查询也可以。
不幸的是,row_number()
仅从 8.0 版开始受支持,但是为了完整起见并在此处包含以说明您应该升级的原因!
with latest as (
select * , Row_Number() over(partition by technology order by date desc) rn
from t
)
select Technology, Students, Amount, Area, Date
from latest
where rn=1