Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 如何使用join语句从另一个表中选择最新记录的值?_Mysql_Sql_Database_Join - Fatal编程技术网

Mysql 如何使用join语句从另一个表中选择最新记录的值?

Mysql 如何使用join语句从另一个表中选择最新记录的值?,mysql,sql,database,join,Mysql,Sql,Database,Join,我试图使用另一个表作为引用来检索表中某列的最新记录值 i、 e: 基本上我想使用Table1作为引用,它包含一个名为Tnumid的列值,该列值从不重复(与id类似,但Tnumid不会跳过一个值)。我想检索第二个表上最新记录的PRnum值 在上面的示例中,我想要的输出基本上是: |id||Tnumid|Prnum| 16 1 422 18 2 890 19 3 450 20 4 700 注意在

我试图使用另一个表作为引用来检索表中某列的最新记录值

i、 e:

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

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

    |id||Tnumid|Prnum|
     16    1     422
     18    2     890
     19    3     450
     20    4     700
注意在Tnum=2的情况下如何选择最新记录的值


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

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

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
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);
请注意,此查询不需要第一个表

编辑:

如果
表1
中缺少某些值,可以使用
左联接
获取它们。例如:

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;

希望它对您有用

选择DISTINCT
Tnumid
id
,Prnum来自
table 2
ORDER BY
id
desc查看这个SO问题的第二个答案-它引用了MySQL文档。如果表1中的值与表2中的行不对应,并且希望突出显示这些情况,那么可能需要与表1进行左连接
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;
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)