Reputation: 9083
Can I define a constraint on a numeric MySQL-column (InnoDB) to only allow values in a certain range?
For example column wavelength
in this table:
CREATE TABLE spectrumdata
(
valueid INT AUTO_INCREMENT,
spectrumset INT NOT NULL,
wavelength DOUBLE NULL,
intensity DOUBLE NULL,
error INT NOT NULL,
status INT NOT NULL,
PRIMARY KEY (valueid),
INDEX spectrumset_idx (spectrumset),
CONSTRAINT spectrumset_fk FOREIGN KEY (spectrumset)
REFERENCES spectrumsets (setid)
)
COLLATE=utf8_general_ci
ENGINE=InnoDB
ROW_FORMAT=DEFAULT
AUTO_INCREMENT=1;
Upvotes: 2
Views: 3123
Reputation: 8431
If you are using InnoDB as Engine sir, you can check this out. As you can see, you can create a new table that contains your limiting values and reference to your field (as Foreign Key) it is now then enforce your constraint with referencial integrity.
UPDATE
try this:
CREATE TABLE allowed_val(
limiting_val DOUBLE NOT NULL,
PRIMARY KEY (limiting_val )
) ENGINE = InnoDB;
INSERT INTO allowed_val( limiting_val) VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),..(1000);
ALTER TABLE spectrumdata
ADD FOREIGN KEY (wavelength) REFERENCES allowed_val(limiting_val);
But you must also alter the spectrumdata
wavelength to NOT NULL
to DEFAULT = 0; to handle null values.
Upvotes: 1