Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL selection join help

I'm having problems figuring out a query for this scenario. I have two tables I want to use in this query, they are like this:

Units
  ID
  Other Data
People
  ID
  UnitID  <-- fk to Units
  Other Data

This is what I want to do:
I want to select all the units that do NOT have a row in the People table linked to them. How can I do this?

like image 724
Malfist Avatar asked May 24 '26 23:05

Malfist


2 Answers

SELECT Units.* FROM Units LEFT JOIN People ON People.UnitID = Units.ID WHERE People.ID IS NULL

or alternatively

SELECT Units.* FROM Units WHERE NOT EXISTS (SELECT 1 FROM People WHERE People.UnitID = Units.ID)

or even

SELECT Units.* FROM Units WHERE Units.ID NOT IN (SELECT UnitID FROM People)
like image 76
araqnid Avatar answered May 27 '26 12:05

araqnid


SELECT * FROM Units  
WHERE NOT EXISTS  
(SELECT * FROM People WHERE UnitID = Units.ID)
like image 45
n8wrl Avatar answered May 27 '26 14:05

n8wrl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!