Easy way to find out if there is a foreign key link from table A to table B?

Suppose I have table A , column id and table B with column A_id . A_id is the id foreign key. Now, if I want to get the entire identifier from A, for which B has a foreign key reference, I can do

 SELECT id FROM A JOIN B ON id = A_id 

However, how can I select all id from A, where B is not referenced? (without selecting all id and subtracting from this subset above)

+4
source share
2 answers
 SELECT id FROM a WHERE id NOT IN ( SELECT a_id FROM b ) 

This will use anti-join: for each entry from a it will look for b to write id (using the index on b.a_id ), and if not found, return the entry.

+3
source
 SELECT A.id FROM A LEFT JOIN B ON A.id = B.A_id WHERE B.A_id IS NULL; 
+2
source

Source: https://habr.com/ru/post/1416603/


All Articles