MySQL Conditional Insert

前端 未结 13 1406
予麋鹿
予麋鹿 2020-11-22 09:51

I am having a difficult time forming a conditional INSERT

I have x_table with columns (instance, user, item) where instance ID is unique. I want to insert a new row

13条回答
  •  耶瑟儿~
    2020-11-22 10:24

    If you add a constraint that (x_table.user, x_table.item) is unique, then inserting another row with the same user and item will fail.

    eg:

    mysql> create table x_table ( instance integer primary key auto_increment, user integer, item integer, unique (user, item));
    Query OK, 0 rows affected (0.00 sec)
    
    mysql> insert into x_table (user, item) values (1,2),(3,4);
    Query OK, 2 rows affected (0.00 sec)
    Records: 2  Duplicates: 0  Warnings: 0
    
    mysql> insert into x_table (user, item) values (1,6);
    Query OK, 1 row affected (0.00 sec)
    
    mysql> insert into x_table (user, item) values (1,2);
    ERROR 1062 (23000): Duplicate entry '1-2' for key 2
    

提交回复
热议问题