I have a problem with UNIQUE CONSTRAINT
.
I need to add constraint based on 2 columns, where one of them need to has specific value.
For example let's say that I have a users
table and it contains users, of course, and the primary key is just an incremented integer.
And I have a configurations
table which has two columns in addition to the configuration columns: user_id
(foreign key of the users
table) and main
which takes 0/1 values.
The logic is as follows: One user can have many configurations, one configuration belongs to one user - as shown in the tables. However, I wanted to restrict it so that one user can only have one main configuration (main = 1) and thought about unique.
I've tried
ALTER TABLE `configurations` ADD UNIQUE `unique_main_user`(`user_id`, `main`);
but that will limit me to one main and one non-main configuration, which is messy.
Is there any possibility to add WHERE statement or any other solution that will allow me to achieve this effect?