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?
SELECT table_a.*
FROM table_a
LEFT JOIN table_b
ON table_a.id = table_b.a_key
WHERE table_b.id IS NULL
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With