【问题标题】:Select latest rows选择最新的行
【发布时间】:2014-03-14 00:30:04
【问题描述】:

我在数据库中有一个表,我想通过某些条件从中选择最新的行。

我做了一个fiddle 来更好地解释我的需求。

如您所见,我已经尝试创建一个查询来获取我想要的数据。但不幸的是,我不仅得到了最新的行,而且实际上得到了符合条件的每一行,但日期。

我尝试用伪 sql 解释我想要什么:

SELECT * FROM test WHERE date = Max(date) AND user = 'Timmy';

编辑: 似乎我想要什么并不完全清楚。 “日期”描述配置文件的创建日期。所以我想获取“Timmy”的所有最新个人资料。

【问题讨论】:

    标签: mysql sql select max


    【解决方案1】:

    如果您想返回与它们关联的最近日期的行,您还可以使用子查询来获取结果:

    select t1.description,
      t1.date,
      t1.profile,
      t1.user,
      Replace(t1.locations, ',', '|') locations
    from test t1
    inner join
    (
      select max(date) date, profile, user
      from test
      group by profile, user
    ) t2
      on t1.user = t2.user
      and t1.date = t2.date
      and t1.profile = t2.profile
    where t1.user = 'Timmy'
    order by t1.profile
    

    SQL Fiddle with Demo

    子查询将返回每个用户和个人资料的最大日期,然后将它加入到您的用户、个人资料和日期表中,以返回每个用户的每个个人资料的最新行(或者,像这里一样,对于特定用户的每个个人资料)。

    【讨论】:

    • '我想获得每一个'Timmy'的最新个人资料——我相信profile也应该包含在GROUP BY
    • @AndriyM 是的,我认为你是正确的。更新了我的答案。谢谢
    【解决方案2】:
    SELECT description,
           date,
           profile,
           user,
           Replace(locations, ',', '|') AS locations
    FROM   test AS t
    WHERE date = (
                      SELECT date
                      FROM test AS tm
                      WHERE tm.user = t.user
                      ORDER BY date DESC
                      LIMIT 1
                     )
      AND user = 'Timmy'
    ORDER  BY profile ;     -- whatever
    

    【讨论】:

    • 这只是一个有点接近解决问题的答案。
    猜你喜欢
    • 2016-04-06
    • 1970-01-01
    • 2018-07-25
    • 2017-06-11
    • 1970-01-01
    • 2020-07-19
    • 1970-01-01
    • 1970-01-01
    • 2018-06-21
    相关资源
    最近更新 更多