简体   繁体   English

带有 ID 不匹配表的连接的 SQL 查询

[英]Sql query with join on table with ID not match

I have two tables.我有两张桌子。

Table 1
Id 
UpdateId
Name

Table 2
Table1ID
UpdateID
Address

Each time user update, system will insert record to table1 .每次用户更新时,系统都会向table1 insert记录。 But for table2 , system only insert record when there is update in address.但是对于table2 ,系统只有在地址有update时才insert记录。

Sample data样本数据

Table 1
1,1,name1
1,2,name1
1,3,name1update
1,4,name1update
1,5,name1
1,6,name2

Table 2表 2

1,1,address
1,4,addressupdate

I want to get the result as following我想得到如下结果

1,1,name1,address
1,2,name1,address
1,3,name1update,address
1,4,name1update,addressupdate
1,5,name1,addressupdate
1,6,name2,addressupdate 

How to make use of join condition to achieve as above?如何利用连接条件来实现如上?

you can use left join when you want to take all columns from left table t1 even though it doesn't match with the other table with column updateid on t2 table.当您想从左表 t1 中获取所有列时,您可以使用左连接,即使它与 t2 表上具有列 updateid 的其他表不匹配。

select t1.id,t1.updateid,t1.name,t2.address from table1 t1
left join table2 t2
on t2.updateid= t1.updateid

you can read more about joins here您可以在此处阅读有关连接的更多信息

You can use a correlated subquery.您可以使用相关子查询。 Here is standard syntax, but it can be easily adapted to any database:这是标准语法,但它可以很容易地适应任何数据库:

select t1.*,
       (select t2.addressid
        from table2 t2
        where t2.table1id = t1.id and
              t2.updateid <= t1.updateid
        order by t2.updateid desc
        fetch first 1 row only
       ) as addressid
from table1 t1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM