Prevent duplicate values in database - mysql

后端 未结 2 919
抹茶落季
抹茶落季 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

    0 讨论(0)
  • 2021-01-22 23:53

    You want a unique index on event_id and day:

    create unique index idx_recurrence_event_day on recurrence(event_id, day)
    

    This will prevent the duplication that you do not want.

    If you already have duplicates there are various ways you can get rid of them. However, it would be easier if you had a unique id for each row, which one reason why an auto-incremented primary key is useful in all tables.

    One way to get rid of them even without a unique id is to use:

    alter ignore table recurrence add unique (event_id, day);
    

    Personally, I don't like this method because adding an index shouldn't delete rows, but this is a valid MySQL extension.

    0 讨论(0)
提交回复
热议问题