【问题标题】:how to retrieve latest data from mysql table out of duplicate records如何从重复记录中检索mysql表中的最新数据
【发布时间】:2021-10-22 14:17:56
【问题描述】:

我正在尝试从我的 sql 表中检索每条记录的最新数据。每条记录都会有重复的数据,并有一些数据更改。我需要检索最新的时间戳数据。有人可以建议在性能方面哪个是最佳解决方案。已经看到了一些内部连接和子查询的解决方案。

下面给出的示例数据

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


my o/p should contain latest data for each tech

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

【问题讨论】:

  • 请分享您使用的mysql版本。
  • 5.6为版本
  • 这是一个关于如何获得所需结果的问题,还是关于您尚未分享的解决方案的性能问题?
  • 我实际上是在寻找以性能为导向的解决方案

标签: mysql query-optimization database-performance groupwise-maximum


【解决方案1】:

一种方法:- *用真实的表名替换表。

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

【讨论】:

  • 我在写同样的查询,你在我面前发帖。快乐编码:)
  • 感谢您编辑其正文,现在查询看起来更美观。欣赏那个伙伴。
  • 感谢 Amit 和 Jatin 的帮助。我想知道是否有任何其他方式我不需要在查询中读取表两次
  • 是的,但不是在你的旧版本的 MySql 中 - 升级时间;-)
  • 能否请您分享解决方案以及该解决方案可用的版本
【解决方案2】:

不需要自联接的最高效的解决方案是使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-26
    • 2013-03-05
    • 2013-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-19
    • 1970-01-01
    相关资源
    最近更新 更多