Franco
Franco

Reputation: 2926

Insert value if value does not exist in another table

I would like to check if all values in column releases.id exist in column charts_extended.release_id

If the value does not exist then I want to insert that value in column releases.id into column charts_extended.release_id

Upvotes: 1

Views: 101

Answers (1)

vhu
vhu

Reputation: 12818

You should first come up with query to check whether the id exists in the table, for example:

SELECT id 
FROM releases
 LEFT JOIN charts_extended ON (release_id=releases.id)
WHERE release_id IS NULL;

If you are happy with that, you can proceed into converting it to an INSERT statement:

INSERT INTO charts_extended (release_id) 
SELECT id 
FROM releases
 LEFT JOIN charts_extended ON (release_id=releases.id)
WHERE release_id IS NULL;

Upvotes: 1

Related Questions