[英]Can I constraint an AutoIncremented column not to accept values from outside?
I have an AutoIncremented column (ID), and I want to have a constraint that only the database ever fills in this column. 我有一个AutoIncremented列(ID),并且我希望有一个约束,只有数据库才能填充此列。 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. 我刚刚在MySQL 5.1.41上进行了测试,它似乎可以正常工作。 If I specify a value for id
in my INSERT
statement, it ignores my value and generates a new surrogate key value. 如果我在INSERT
语句中为id
指定一个值,它将忽略我的值并生成一个新的代理键值。
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 |
+----+-------+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.