【问题标题】:How to use join statement to select the latest recorded value from another table?如何使用 join 语句从另一个表中选择最新记录的值?
【发布时间】:2016-06-23 18:42:35
【问题描述】:

我正在尝试使用另一个表作为参考来检索表中列的最新记录值。

即:

Table1
        |id|Tnumid|
         13    1
         14    2
         15    3
         16    4
Table2
        |id|Tnumid|PRnum|Timestamp
         16    1   422   1455815894
         17    2   560   1455815895 
         18    2   890   1455815896
         19    3   450   1455815897
         20    4   700   1455815898

基本上我想使用 Table1 作为参考,它包含一个名为 Tnumid 的列值,它从不重复(类似于 id,但 Tnumid 不会跳过一个值)。我想检索第二张表上 PRnum 的最新记录值。

基本上我在上面的例子中想要的输出是:

    |id||Tnumid|Prnum|
     16    1     422
     18    2     890
     19    3     450
     20    4     700

注意在 Tnum=2 的情况下如何选择最新记录的值。

所以我想从 Table2 中选择 PRnum,但我需要准确检索 Tnumid 的值的数量,始终选择最新记录的值。如何使用 JOIN 语句或类似的东西来做到这一点......?我是 MySQL 新手。非常感谢。

【问题讨论】:

标签: mysql sql database join


【解决方案1】:
with lastvalue as
(
  select * ,row_number() over(PARTITION by tnumid order by id ) as laestval from Table_2 
)
  select * from lastvalue as cte  where laestval =(select max (laestval) from lastvalue where tnumid =cte.Tnumid)

希望对你有用

【讨论】:

    【解决方案2】:

    您可以预先聚合数据并将结果连接在一起:

    select t2.*
    from table2 t2 join
         (select trumid, max(id) as maxid
          from table2
          group by t2
         ) tt2
         on tt2.trumid = t.trumid;
    

    另一种方法在where 子句中执行此操作:

    select t2.*
    from table2 t2
    where t2.id = (select max(tt2.id) from table tt2 where tt2.trumid = t2.trumid);
    

    请注意,此查询不需要第一个表。

    编辑:

    如果table1 中的某些值丢失,您可以使用left join 获取它们。例如:

    select t2.id, trumid, t2.prnum
    from table1 t1 left join
         table2 t2
         using (trumid)
    where t2.id = (select max(tt2.id) from table tt2 where tt2.trumid = t2.trumid) or
          t2.id is null;
    

    【讨论】:

    • 如果表 1 中的值对应于表 2 中的任何行并且您想突出显示这些情况,则可能需要与表 1 进行左连接
    【解决方案3】:
    select max(t1.id),t1.tnumid,max(t2.prnum)
    from table1 t1
    inner join table2 t2 on t1.tnumid =t2.tnumid
    group by t1.tnumid
    

    【讨论】:

      猜你喜欢
      • 2019-09-02
      • 2019-06-03
      • 2014-10-12
      • 1970-01-01
      • 2021-08-05
      • 2021-12-31
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多