Mysql
 sql >> Datenbank >  >> RDS >> Mysql

MySQL Insert if Bedingung

Sie können so etwas tun:

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);

BEARBEITEN:

Hoppla. Das obige funktioniert in MySQL nicht, da ein from fehlt -Klausel (funktioniert aber auch in vielen anderen Datenbanken). In jedem Fall schreibe ich dies normalerweise, indem ich die Werte in eine Unterabfrage schreibe, damit sie nur einmal in der Abfrage erscheinen:

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
                     );