I want a table with an integer column, that may or may not be filled (it is a social security number). But if it is filled, I want it to be UNIQUE : there cannot be two entries of the same number.
Using a unique constraint won't work cause integer won't accept NULL values, and MySQL detects multiple 0 values.
How can I set a unique constraint on 开发者_Go百科an integer with a default value ? Or how can I set the integer column to accept NULL values ? (this question takes it for granted : MySQL Foreign Key Constraint - Integer Column but I can't)
create table test (
myint INT NULL, UNIQUE INDEX (myint)
);
This will allow a unique constraint on any integers added but will allow multiple NULL values to be entered.
MySQL treats NULL as 'unknown' value so cant possibly do a comparison to see if a like value is already there 'unknown' !== 'unknown'.
This also depends on which database engine you are using, the above holds true for MyISAM and InnoDB
Please see the code below:
ALTER TABLE test MODIFY myint INT NULL
ALTER TABLE test ADD UNIQUE INDEX (myint)
It works when data inputs are directly from MySQL (PHPMyadmin), saved as NULL, but a php script saves it as zeroes, and so it does not allow multiple entries.
精彩评论