[英]MySQL: Can I constraint column values in one table to values in a column in another table, by DB design only?
Example: 例:
Table "persons", Column "surname" may only contain values predefined in 表“人员”,列“姓”只能包含在中预定义的值
Table "names", Column "surnames", which would contain a collection of surnames acceptable for the purpose. 表“名称”,列“姓氏”,其中将包含为此目的可接受的姓氏集合。
Can I achieve this by design (ie without involving any validation code)? 我可以通过设计实现此目标(即不涉及任何验证代码)吗? On a MyISAM table? 在MyISAM表上? No? 没有? On InnoDB? 在InnoDB上?
Thank you. 谢谢。
What you're asking for is a foreign key constraint. 您要的是外键约束。 You'd need to use InnoDB - quote : 您需要使用InnoDB-quote :
For storage engines other than InnoDB, MySQL Server parses the FOREIGN KEY syntax in CREATE TABLE statements, but does not use or store it. 对于InnoDB以外的存储引擎,MySQL Server在CREATE TABLE语句中解析FOREIGN KEY语法,但不使用或存储它。
To add a foreign key constraint within the CREATE TABLE statement for PERSONS
: 要在CREATE TABLE语句中为PERSONS
添加外键约束:
FOREIGN KEY (surname) REFERENCES names(surnames)
Using an ALTER TABLE statement if the tables already exist: 如果表已经存在,请使用ALTER TABLE语句:
ALTER TABLE persons
ADD CONSTRAINT FOREIGN KEY (surname) REFERENCES names(surname)
Be aware that if you use the ALTER TABLE
statement, the data in the PERSONS
table can only contain surname values that exist in the NAMES.surname
table - it can not be applied until after the data has been fixed. 请注意,如果您使用ALTER TABLE
语句,在数据PERSONS
表只能包含存在于姓值NAMES.surname
表-它不能被应用,直到数据已被固定后。
For MyISAM tables you can achieve desired functionality by using triggers. 对于MyISAM表,您可以通过使用触发器来实现所需的功能。
For instance (validate insert), 例如(验证插入),
DELIMITER //
CREATE DEFINER=`root`@`localhost` TRIGGER BEFORE INSERT ON persons
FOR EACH ROW
BEGIN
DECLARE tmp_surname varchar(100);
SELECT surname into tmp_surname FROM names WHERE surname = NEW.surname;
IF (tmp_surname IS NULL) THEN
INSERT INTO t1(id,value) VALUES('aaa'); #raise an 'exception'
END IF;
END;//
delimiter;
Mysql doesn't have exceptions, but you can terminate execution(and, consequently, 'rollback' changes) by creating an invalid statement Mysql没有异常,但是您可以通过创建无效的语句来终止执行(并因此执行“回滚”更改)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.