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
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
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.