Prevent duplicate values in database - mysql

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

提交回复
热议问题