The restriction you are looking for is the validation restriction.
CREATE TABLE test ( a varchar(10), b varchar(10), c varchar(10), x integer, y integer, z integer, CONSTRAINT chk_X_Nulls CHECK ((a is null and x is null) or (a is not null and x = 1)), CONSTRAINT chk_Y_Nulls CHECK ((b is null and y is null) or (b is not null and y = 1)), CONSTRAINT chk_Z_Nulls CHECK ((c is null and z is null) or (c is not null and z = 1)) );
Unfortunately this is not implemented in MySQL . There is an open bug report for 2004 for this feature, so don't expect to see it anytime soon.
Others answered that you can use triggers or views to achieve the desired result, and these are the correct answers for MySQL.
You can also partially limit your data with simple tricks:
- Set the data type
x, y, z to enum('1') . This will prevent the insertion of values other than null and '1' , but does not guarantee that the values are correct. - If
a, b, c has a limited range of possible values, you can create foreign key constraints for other tables and populate these tables with any possible value of a, b, c - You can create an event to update
x, y, z on a schedule (for example, once an hour or once a day). Values for x, y, z can be corrected if they are erroneous.
You can see the check constraint in action with PostGreSQL here
If you need further advice, explain why triggers are not suitable for your task.
dwurf source share