简体   繁体   中英

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)

I have two tables, tableA and tableB. They both have columns (vehicle_make and vehicle_model).

I need all make/model of the vehicles from tableA that are not present in tableB.

Basically I need to find new make and models. tableB is currently I am using in my project and tableA is generic data with all the vehicles in the US.

You can use NOT IN operator.

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

Using a coorlated subquery: usually the most efficient with exists.

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

Using an outer join (if you needed data from table B on the records that did exist... like a count of records from B for each make/model

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 works (unless you can have null values)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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