I have an AutoIncremented column (ID), and I want to have a constraint that only the开发者_运维问答 database ever fills in this column. Is there a constraint for that?
I don't think there's a declarative constraint that can do this.
You can do it using a trigger, for example:
DELIMITER //
CREATE TRIGGER ForceId BEFORE INSERT ON MyTable
FOR EACH ROW
BEGIN
SET NEW.id = DEFAULT;
END //
DELIMITER ;
I just tested this on MySQL 5.1.41 and it seems to work. If I specify a value for id
in my INSERT
statement, it ignores my value and generates a new surrogate key value.
INSERT INTO MyTable (id, name) VALUES (DEFAULT, 'Bill');
INSERT INTO MyTable (id, name) VALUES (123, 'John');
SELECT * FROM MyTable;
+----+-------+
| id | name |
+----+-------+
| 1 | bill |
| 2 | john |
+----+-------+
精彩评论