22

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)

8
  • 1
    May I suggest LEFT JOIN? Commented Mar 24, 2014 at 21:47
  • 1
    inner join means "where both records are equal". so it won't work. as Zdavko just posted... you want a left outer join, meaning give me all of this on the left, regardless of what matches on the right Commented Mar 24, 2014 at 21:48
  • With LEFT JOIN it crashes (just the same as using the nested SELECT). Please note, I have 44K tracks and 10K albums. Also tried directly with MySQL command line
    – Martin
    Commented Mar 24, 2014 at 21:58
  • 1
    What do you mean "crashes"? Is it just taking a long time to execute? If so, you probably need indices on the id and album_id columns. With the appropriate indices, 44K tracks and 10K albums should be a piece of cake. I have a related pair of tables with 15K and 80K rows respectively and a LEFT JOIN on them takes less than 0.1 seconds.
    – Kryten
    Commented Mar 24, 2014 at 22:05
  • track.id is set as Primary, while track.album_id has an index yes @Kryten what I meant is that it freezes and does not return results (after a good few minutes I manually interrupt the execution)
    – Martin
    Commented Mar 24, 2014 at 22:17

2 Answers 2

38
SELECT a.id 
FROM album a
LEFT JOIN track t ON a.id = t.album_id
WHERE t.id IS NULL
28

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

1
  • 4
    not exists is not to be used if you are aiming performance. It is a performance killer.
    – aidonsnous
    Commented Mar 21, 2018 at 14:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.