Reputation: 2500
I have table:
id emp_id company role
1 3 1 0
2 2 1 0
3 1 1 1
I need to restrict adding 2 employees for a company with role = 1
. Like unique key for company & role, but only for role = 1;
In other words, INSERT INTO table (emp_id, company, role) (4, 1, 1)
must fail.
The only way to do it in my head - use triggers. Are there another way?
Upvotes: 1
Views: 57
Reputation: 1270391
ONe way to do this in MySQL is to change the role
so it contains 1 or NULL
rather than or
0. A unique index ignores
NULL`s, so you can do:
create unique index idx_table_company_role on table(company, role);
You can then create a view on the table, if you want to see 0 and 1:
create view v_table as
select t.*, (case when role = 1 then 1 else 0 end) as newrole
from table;
Upvotes: 1
Reputation: 93734
Create a filtered index
create unique index [Indexname]
on [Yourtable](company,role)
where [role] = 1
Upvotes: 0