Ryan Castle Ryan Castle - 5 months ago 7
MySQL Question

SQL - Insertion of row with selection from other row IF the row doesn't exits

So, I'm wanting to insert a row into the table

teams_views
IF the row doesn't already exist. This is a simple query, but I'm having issues including a selection into this query. Basically, one of the fields in the row is in need of being fetched from another table.

Here's a breakdown of what I am wanting to build in SQL:

INSERT INTO
teams_views (col1, col2)
VALUES
(SELECT col1 FROM teams WHERE teams.identifier = 1234, col2)
WHERE
teams_views.col1
IS NULL


What can I do to get this query work?
Thanks.

Answer
INSERT INTO teams_views (col1, col2)
SELECT t.col1 ,  t.col2
FROM teams t
WHERE t.identifier = 1234
AND NOT EXISTS (SELECT 1 FROM teams_views
                WHERE t.col1 = col1)