How to Insert into the table if the record does not exist

Asked

Viewed 1,113 times

2

How to insert in the table if there is no record, as for example there is the table turma_materia, has the following information:

+----+-------+---------+
| ID | turma | materia |
+----+-------+---------+
| 1  |  1    |  1      |
| 2  |  1    |  2      |
| 3  |  2    |  2      |

If you try to insert Class 1 with Class 1, it will check if you have, if you do not have Index, if you do not have it

1 answer

3


You can use a SELECT instead of VALUES in the INSERT:

INSERT INTO turma_materia(ID, turma, materia)
SELECT 1, 1, 1
 WHERE NOT EXISTS (SELECT 1
                     FROM turma_materia
                    WHERE ID = 1
                      AND turma = 1
                      AND materia = 1);

If you only want to set the values once, you can use a subquery in the FROM:

INSERT INTO turma_materia(ID, turma, materia)
SELECT x.ID, x.turma, x.materia
  FROM (SELECT 1 AS ID,
               1 AS turma,
               1 AS materia) x
 WHERE NOT EXISTS (SELECT 1
                     FROM turma_materia tm
                    WHERE tm.ID = x.ID
                      AND tm.turma = x.turma
                      AND tm.materia = x.materia);
  • It worked, thank you very much

  • 1

    Better would be a UNIQUE index, no?

  • @Bacco opa, had not seen the comment. I saw now the other reply, thank you, I will give a UP there. Really would be the best solution

Browser other questions tagged

You are not signed in. Login or sign up in order to post.