Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find rows in A that don't have an associated row in B, where the FK is on B?

What I've been doing is

SELECT * FROM a LEFT JOIN b ON b.a_id=a.id WHERE b.id IS NULL

Basically, I'm trying to find the rows of a that don't have an associated b, where the foreign key is stored on b. Is this the proper way to do it, or there a different kind of join to do this?

like image 532
mpen Avatar asked Dec 07 '22 21:12

mpen


1 Answers

You are looking for NOT EXISTS:

SELECT 
  * 
FROM 
  a
WHERE
  NOT EXISTS (SELECT 1 FROM b WHERE a_id = a.id)

Having an index on b.a_id helps the performance of this query.

like image 104
Tomalak Avatar answered Dec 10 '22 13:12

Tomalak