从两个表中查找不匹配的数据

时间:2018-10-26 03:31:29

标签: sql join

我正在尝试编写查询以查找另一个表中没有匹配记录的记录。

例如,我有两个表,其结构如下所示:

表1

Address ID | Address Type
AD7233654242 | Condo
AD7233654242 | Condo
AD7233654243 | Apartment
AD7233654244 | Condo

表2

Address ID | Address Type
AD7233654242 | Condo
AD7233654242 | Apartment
AD7233654243 | Apartment
AD7233654244 | Condo

根据上面的数据,您会发现地址ID AD7233654242具有不匹配的地址类型。表A显示公寓,表B显示公寓。因此,在查询结果中,我想从两个表中分配地址ID和地址类型。

关于查询的任何建议吗?

4 个答案:

答案 0 :(得分:1)

您可以使用join类型查询匹配和不匹配的记录。以下是不同联接的示例。

declare @tbl1 table(AddressID varchar(20), AddressType varchar(50))
declare @tbl2 table(AddressID varchar(20), AddressType varchar(50))

insert @tbl1(AddressID,AddressType) values
('AD7233654242', 'Condo'),
('AD7233654242', 'Condo'),
('AD7233654243', 'Apartment'),
('AD7233654244', 'Condo'),
('AD7233654245', 'Condo')--my sample

insert @tbl2(AddressID,AddressType) values
('AD7233654242', 'Condo'),
('AD7233654242', 'Apartment'),
('AD7233654243', 'Apartment'),
('AD7233654244', 'Condo')

--records in @tbl1 matching @tbl2
select t1.AddressID addrId_1, t1.AddressType addrType_1, t2.AddressID addrId_2, t2.AddressType addrType_2
from @tbl1 t1 -- 1st or left table
inner join @tbl2 t2 --2nd or right table
on t1.AddressID=t2.AddressID and t1.AddressType=t2.AddressType

--records in @tbl1 not matching @tbl2
select t1.AddressID, t1.AddressType
from @tbl1 t1
left join @tbl2 t2 on t1.AddressID=t2.AddressID and t1.AddressType=t2.AddressType
where t2.AddressID is null

--records in @tbl2 not matching @tbl1
select t2.AddressID, t2.AddressType
from @tbl1 t1
right join @tbl2 t2 on t1.AddressID=t2.AddressID and t1.AddressType=t2.AddressType
where t1.AddressID is null

--all mismatches
select t1.AddressID addrId_1, t1.AddressType addrType_1, t2.AddressID addrId_2, t2.AddressType addrType_2
from @tbl1 t1
full join @tbl2 t2 on t1.AddressID=t2.AddressID and t1.AddressType=t2.AddressType
where t1.AddressID is null or t2.AddressID is null

答案 1 :(得分:0)

一个简单的连接应该在这里工作:

SELECT
    t1.AddressID,
    t1.AddressType,
    t2.AddressType
FROM Table1 t1
INNER JOIN Table2 t2
    ON t1.AddressID = t2.AddressID AND t1.AddressType <> t2.AddressType;

这实际上将返回两个AD7233654242的记录。如果您有预期的输出,我们可以使用该逻辑修改以上查询。

答案 2 :(得分:0)

您可以尝试在条件为空的情况下使用左联接和null

SELECT t1.AddressID, t1.AddressType,t2.AddressType
FROM Table1 t1
left JOIN Table2 t2
    ON t1.AddressID = t2.AddressID AND t1.AddressType=t2.AddressType
where t2.AddressID is null

答案 3 :(得分:0)

我想这就是您要问的。。

SELECT * from table1 T1
where exists (
SELECT * from table2 T2
where T1.AddressID = T2.AddressID
and T1.AddressType<>T1.AddressType)

UNION 

SELECT * from table1 T2
where exists (
SELECT * from table2 T1
where T1.AddressID = T2.AddressID
and T1.AddressType<>T1.AddressType)