I am trying to run an SQL query in phpMyAdmin in a MySQL database in order to get records that do not have corresponding records in another table.
E.g.
**album**
id, name
**track**
id, album_id, name
I need all album records that do not have relative track records.
I have tried
SELECT album.id
from album
WHERE album.id NOT IN (
SELECT track.album_id
FROM track
WHERE 1
GROUP BY track.album_id
)
But unfortunately this crashes the MySQL service
I have also tried
SELECT a.id FROM album a
INNER JOIN track t
ON a.id = t.album_id
WHERE t.id IS NULL
but this doesn't work as expected (returns no results)
We can get the records in one table that doesn't exist in another table by using NOT IN or NOT EXISTS with the subqueries including the other table in the subqueries.
The SQL LEFT JOIN returns all rows from the left table, even if there are no matches in the right table. This means that if the ON clause matches 0 (zero) records in the right table; the join will still return a row in the result, but with NULL in each column from the right table.
You can use EXISTS to check for the absence of a record in the related table.
SELECT album.id
FROM album
WHERE NOT EXISTS (
SELECT *
FROM track
WHERE track.album_id = album.id
);
See: http://dev.mysql.com/doc/refman/5.0/en/exists-and-not-exists-subqueries.html
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