Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query to select unreferenced rows

Tags:

sql

mysql

I'm having a brain-dead moment... I have two tables described by:

CREATE TABLE table_a (
    id             INTEGER          PRIMARY KEY AUTO_INCREMENT,
    name           VARCHAR(255)     NOT NULL
    UNIQUE (name))

CREATE TABLE table_b (
    id             INTEGER          PRIMARY KEY AUTO_INCREMENT,
    a_key          INTEGER          NOT NULL,
    other_stuff    VARCHAR(255)     NOT NULL,
    FOREIGN KEY(a_key)  REFERENCES table_a(id)
         ON DELETE CASCADE)

How can I select all rows from table_a that do not have an entry in table_b.a_key?

like image 663
user23167 Avatar asked Feb 05 '09 12:02

user23167


2 Answers

SELECT table_a.*
FROM table_a
    LEFT JOIN table_b
        ON table_a.id = table_b.a_key
WHERE table_b.id IS NULL
like image 160
LukeH Avatar answered Oct 01 '22 20:10

LukeH


Naively, you can use a NOT EXISTS subquery:

SELECT A.*
FROM table_a A
WHERE NOT EXISTS (
  SELECT 1
  FROM table_b B
  WHERE B.a_key = A.id
)

You can also try an outer join. But they'll usually optimize to the same query internally.

like image 23
Welbog Avatar answered Oct 01 '22 20:10

Welbog