Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql select records that don't have relation in a second table

Tags:

sql

mysql

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)

like image 785
Martin Avatar asked Mar 24 '14 21:03

Martin


People also ask

How do I select data FROM one table is not in another table?

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.

How would you return data FROM 2 tables even if there are no matches?

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.


1 Answers

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

like image 60
Jeremy Avatar answered Oct 19 '22 06:10

Jeremy