【问题标题】:select latest (up to some date ) records of each variable from mysql table [duplicate]从mysql表中选择每个变量的最新(直到某个日期)记录[重复]
【发布时间】:2017-08-03 11:33:40
【问题描述】:

表结构示例

VarName   Date   Machine
-------------------------
A    date1       machine1
B    date2       machine1
A    date3       machine2
C    date4       machine2
A    date5       machine1
C    date6       machine1
A    date7       machine1

我试图从我的数据库中过滤的内容应该如下所示:

  VarName   Date   Machine
    -------------------------
    A    date1       machine1
    B    date2       machine1
    C    date6       machine1

每个变量只能被选择一次,并且每个变量必须是截至特定日期的最新记录。我的陈述条件是(WHERE date <= 'some date' AND machine='SomeMachineName')。加入声明可能是解决方案,但我尝试过的任何事情都没有运气。

感谢您的帮助

【问题讨论】:

    标签: php mysql sql join


    【解决方案1】:

    一种方法在where 子句中使用相关子查询:

    select t.*
    from t
    where t.date = (select max(t2.date)
                    from t t2
                    where t2.varname = t.varname and
                          t2.date <= @date
                   );
    

    为了提高性能,您需要在t(varname, date) 上建立索引。

    【讨论】:

    • 非常感谢。这就是我一直在寻找的
    【解决方案2】:

    有一个返回每个 VarName 的最后日期的派生表(子查询)。加入该结果:

    select t1.*
    from tablename t1
    join (select VarName, max(Date) Date
          from tablename
          group by VarName) t2
      on t1.Varname = t2.VarName and t1.Date = t2.Date   
    

    【讨论】:

    • 您缺少 WHERE 子句,请参阅 Gordon 的回答。因此,在发布之前花时间确保您的答案是正确的非常重要:-)
    • @TimBiegeleisen,是的,也是 OP 应该发布查询尝试的原因之一......
    • @jarlh 或者也许是在提供足够信息之前我们应该拒绝发布答案的原因!
    猜你喜欢
    • 2021-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多