l--*_*''' 7 mysql sql foreign-keys
我在这里得到了另一个问题的答案:
这是一个很好的答案,但我不了解有关引用的一点.我可以做SQL语句,但我从未使用过引用.
Mar*_*ers 12
REFERENCES关键字是外键约束的一部分,它使MySQL要求引用表的指定列中的值也存在于引用表的指定列中.
这可以防止外键引用不存在或被删除的ID,并且可以选择阻止您在仍然引用行时删除它们.
一个具体示例是,如果每个员工都必须属于某个部门,那么您可以通过employee.departmentid引用添加外键约束department.id.
运行下面的代码来创建两个测试表tablea和tableb其中列a_id中tableb引用的主键tablea.tablea填充了几行.
CREATE TABLE tablea (
id INT PRIMARY KEY,
foo VARCHAR(100) NOT NULL
) Engine = InnoDB;
INSERT INTO tablea (id, foo) VALUES
(1, 'foo1'),
(2, 'foo2'),
(3, 'foo3');
CREATE TABLE tableb (
id INT PRIMARY KEY,
a_id INT NOT NULL,
bar VARCHAR(100) NOT NULL,
FOREIGN KEY fk_b_a_id (a_id) REFERENCES tablea (id)
) Engine = InnoDB;
Run Code Online (Sandbox Code Playgroud)
现在尝试以下命令:
INSERT INTO tableb (id, a_id, bar) VALUES (1, 2, 'bar1');
-- succeeds because there is a row in tablea with id 2
INSERT INTO tableb (id, a_id, bar) VALUES (2, 4, 'bar2');
-- fails because there is not a row in tablea with id 4
DELETE FROM tablea WHERE id = 1;
-- succeeds because there is no row in tableb which references this row
DELETE FROM tablea WHERE id = 2;
-- fails because there is a row in tableb which references this row
Run Code Online (Sandbox Code Playgroud)
重要说明:两个表都必须是InnoDB表,否则将忽略约束.