MySQL - unique with exemption

Is there a way in mySQL to specify a UNIQUE constraint on multiple columns with a constraint to a specific value of a specific column?

Example:

AB
......
1 0
1 1
1 2
2 1
3 0
3 2

in the above table, if B is 0 then it can have the same set of values ​​(rows) in the table (duplicate), and if B is 1 then it should not take the same set of A, B pair. For example: in this case it should accept any number of pairs (A, B) = (1,0), (3,0) since B is 0, but it should not accept duplicate (1,1), (1, 2), (2.1), (3.2).

+3


source to share


1 answer


MySQL allows you to duplicate already with multiple columns UNIQUE constraints if any of the column values ​​in the constraint is NULL. Perhaps you could replace 0 with NULL.



+1


source







All Articles