Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mySql query to find records not present in another table

Tags:

mysql

I had two mySql tables of CARS and DRIVERS with the attribute licenseNumber
as a foreign key.

What would be the query to find the names of the drivers who did not have a car?

I was thinking:

SELECT DISTINCT D.name
FROM drivers D, cars C
WHERE 
 D.licenseNumber = C.licenseNumber AND 
  D.licenseNumber NOT IN (SELECT licenseNumber FROM cars)

But that doesn't return anything.
I have a feeling I'm overthinking it a bit.
Any help?

like image 344
bananamana Avatar asked Dec 09 '22 12:12

bananamana


2 Answers

SELECT D.name 
FROM drivers D
WHERE NOT EXISTS(SELECT * FROM cars c 
                 WHERE D.licenseNumber = C.licenseNumber)
like image 198
Martin Smith Avatar answered Dec 27 '22 00:12

Martin Smith


It is not possible for any row to match that query (if licenseNumber was not in the cars table, how would cars.licenseNumber = drivers.licenseNumber?).

SELECT DISTINCT name FROM drivers WHERE licenseNumber NOT IN (SELECT licenseNumber FROM cars)
like image 22
Dan Grossman Avatar answered Dec 27 '22 02:12

Dan Grossman