簡體   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