繁体   English   中英

两个共有2列的SQL表需要在表A中但不在表B中的记录(列1相同,但列2不同)

[英]two SQL tables with 2 columns in common, need records that are in table A but not in table B (column 1 is same in both but different column 2)

我有两个表,tableA和tableB。 它们都有列(vehicle_make和vehicle_model)。

我需要tableA中所有不在tableB中的车辆的品牌/型号。

基本上我需要找到新的品牌和型号。 我目前在我的项目中使用的是tableB,而tableA是美国所有车辆的通用数据。

您可以使用NOT IN运算符。

SELECT DISTINCT vehicle_make, vehicle_model
FROM tableA
WHERE (vehicle_make || vehicle_model) NOT IN 
      (SELECT DISTINCT (vehicle_make || vehicle_model)
       FROM tableB)

使用协调的子查询:通常最高效的with存在。

SELECT vehicle_make, vehicle_model
FROM tableA A
WHERE Not Exists (SELECT * 
                  FROM tableB 
                  WHERE A.vehicle_make = B.Vehicle_make
                    and A.vehicle_model = B.Vehicle_model

使用外部联接(如果您需要表B上确实存在的记录上的数据...像每个品牌/型号来自B的记录计数

SELECT A.vehicle_make, A.vehicle_model, count(B.*)
FROM tableA A
LEFT JOIN tableB B
 on A.vehicle_make = B.Vehicle_make
and A.vehicle_model = B.Vehicle_model
WHERE B.Vehicle_make is null
GROUP BY A.vehicle_make, A.vehicle_model

In作品中(除非您可以具有空值)

select a.*
from TableA a
left outer join TableB b 
       on a.vehicle_make = b.vehicle_make 
      and a.vehicle_model = b.vehicle_model
where b.vehicle_make is null

暂无
暂无

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

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