Sql 条件联接,然后保存表

Sql 条件联接,然后保存表,sql,join,Sql,Join,我有两个共享字段的表:ID、全名、DoB。 第二个表的ID为NA,因此我必须以全名和DoB加入。 比如: Select * from table1 t1 left outer join table2 t2 on t1.mrn = t2.mrn and (t1.mrn is null and t1.dob = t2.dob and t1.fullname = t2.fullname) 或 不知道如何使

我有两个共享字段的表:ID、全名、DoB。 第二个表的ID为NA,因此我必须以全名和DoB加入。 比如:

Select * from table1 t1
     left outer join  table2 t2
       on  t1.mrn = t2.mrn
       and (t1.mrn is null 
             and t1.dob = t2.dob
             and t1.fullname = t2.fullname)

不知道如何使用case在ID中有空时创建条件语句,那么我希望sql使用全名和DOB进行连接

此外,将此查询另存为新表


PS:我在R中使用sqldf来练习sql。非常感谢您的帮助。

好吧,您可以不检查mrn也可以不检查mrn。但无论哪种方式,您都需要使用或:

Select * from table1 t1
     left outer join  table2 t2
       on  t1.mrn = t2.mrn
       or (t1.dob = t2.dob and t1.fullname = t2.fullname)
或:

要使用上述查询创建新表,请执行以下操作:

select * 
into NewTableName
from table1 t1
     left outer join  table2 t2
       on  t1.mrn = t2.mrn
       or (t1.dob = t2.dob and t1.fullname = t2.fullname)

连接谓词是布尔表达式
a=b和c=d
并不意味着
包括a=b的结果和c=d的结果
它意味着
在a=b和c=d同时给出结果
。这些布尔表达式是逐行计算的。因此,根据下面的答案;您需要
(mrn匹配)或(姓名匹配和dobs匹配)
啊,好的,谢谢。以及如何将此查询保存为新表。(对不起,我的背景是R,所以我习惯在查询之外使用as.data.frame)。@NaomiTinga。对于您正在使用的任何数据库,您都可以使用
create table as
或等效的方法。@NaomiTinga正如Gordon提到的,取决于数据库,您可以使用“create table as”或我添加到答案中的查询
Select * from table1 t1
     left outer join  table2 t2
       on  t1.mrn = t2.mrn
       or (t1.mrn is null and t1.dob = t2.dob  and t1.fullname = t2.fullname)
select * 
into NewTableName
from table1 t1
     left outer join  table2 t2
       on  t1.mrn = t2.mrn
       or (t1.dob = t2.dob and t1.fullname = t2.fullname)