![](/img/trans.png)
[英]Retrieve columns from table A in comparsion to table B column values where there is no common relationship between two tables
[英]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.