简体   繁体   English

sql server左联接并且不存在的地方比较两个不同数据库中两个表之间的记录

[英]sql server left join and where not exist to compare record between two tables in two different databases

I have write a sql server script which will do the following 我已经写了一个sql server脚本,它将执行以下操作

  1. select records from one table1 in a database1 based on two fields like so 根据两个字段,从数据库1的一个表1中选择记录,如下所示

    select * from table1FromDB1 where ID = 5 and TYPE = "TeST"

  2. I need to do another select on another different table like Table2 in a different database like DB2 perform the logic 我需要在另一个数据库(例如DB2)中对另一个不同的表(例如Table2进行另一个选择,以执行逻辑

If the records select from Table1 exist in Table2 take the one from Table2 , else if records in Table1 does not exist in table2 , use the one in table1 如果记录从选择Table1中存在的Table2采取从一个Table2 ,否则,如果在记录Table1中不存在table2中,使用一个在table1

I am not good with left join or where not exist but I am told that is how to do it. 我不擅长左联接或不存在联接,但被告知这是怎么做的。

so here is my first attempt 所以这是我的第一次尝试

select * from table1 t1
left join db2.table2 as t2 on t1.id = t2.id and t1.type = t2.type 
where not exists  (???) 
where ID = 5 and TYPE = "Test" 

Any help is appreaciated. 任何帮助表示赞赏。 Thanks. 谢谢。

With a LEFT JOIN, you will get all records from table 1 and the values from table 2 that are not matched through the ON conditions will return a NULL value. 使用LEFT JOIN,您将获得表1中的所有记录,而表2中通过ON条件不匹配的值将返回NULL值。 In your example, we want to use the value from table 1 when we see a NULL value from table 2. SQL Server has ISNULL() that can accomplish this. 在您的示例中,当我们从表2中看到NULL值时,我们想使用表1中的值。SQLServer具有可以完成此操作的ISNULL()。 ISNULL() will check to see if the first value in the list is null, and if it is null, it will return the second value in the list. ISNULL()将检查列表中的第一个值是否为空,如果为空,则将返回列表中的第二个值。 If the first value is not null, it will use the first value. 如果第一个值不为null,它将使用第一个值。 For more than 2 values, consider COALESCE(). 对于两个以上的值,请考虑使用COALESCE()。

SELECT ISNULL(t2.yourvalue, t1.yourvalue)
FROM table1 t1
LEFT JOIN table2 t2
ON t1.id = t2.id 
AND t1.type = t2.type

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

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