Prevent duplicate values in database - mysql

后端 未结 2 923
抹茶落季
抹茶落季 2021-01-22 23:08

I have one table that store values about recurrence of some events, for example, the event with id=1 occurs in Monday, Wednesday and Friday, and the event with

2条回答
  •  太阳男子
    2021-01-22 23:50

    Mr. Linoff provided the right way but if you cant's modify your schema, you can also check on insert with row subquery:

    insert into table_name
    select 1, 2, 'Monday' from dual
    where (1,2, 'Monday') not in
    (select id,event_id, day from table_name);
    

    SQLFIDDLE DEMO

    Or use where not exists

    insert into table_name
    select 1, 2, 'Monday' from dual
    where not exists
    (select 1,2, 'Monday' from table_name);
    

    SQLFIDDLE DEMO

提交回复
热议问题