sql >> Base de Datos >  >> RDS >> Mysql

MySQL Insertar si Condición

Puedes hacer algo como esto:

insert into cats_rel(cat_id, post_id)
    select 11, 32
    where not exists (select 1 from cats_rel where cat_id = 11 and post_id = 32);

EDITAR:

Ups. Lo anterior no funciona en MySQL porque falta un from cláusula (aunque funciona en muchas otras bases de datos). En cualquier caso, suelo escribir esto poniendo los valores en una subconsulta, para que solo aparezcan en la consulta una vez:

insert into cats_rel(cat_id, post_id)
    select toinsert.cat_id, toinsert.post_id
    from (select 11 as cat_id, 32 as post_id) toinsert
    where not exists (select 1
                      from cats_rel cr
                      where cr.cat_id = toinsert.cat_id and cr.post_id = toinsert.post_id
                     );