Bogdan Goncharenko
Bogdan Goncharenko

Reputation: 107

How to insert a row if the value from other table doesn't exist?

I have three tables: person, lead and legal_entity. legal_entity.personId references person.Id and lead.personId also references person.Id. What I need to do is to insert a new row with the value of legal_entity.personId to the lead table if it doesn't exist already. I need to do it for every row from legal_entity table. I have no idea how to do something like this.

Upvotes: 0

Views: 308

Answers (1)

Bogdan Goncharenko
Bogdan Goncharenko

Reputation: 107

INSERT INTO lead (person_id)
SELECT p.id
FROM legal_entity le
INNER JOIN person p on le.person_id = p.id
LEFT JOIN lead l on p.id = l.person_id
WHERE l.id IS NULL

Upvotes: 1

Related Questions