在MYSQL中使用引用

l--*_*''' 7 mysql sql foreign-keys

我在这里得到了另一个问题的答案:

用于聊天的DB Schema?

这是一个很好的答案,但我不了解有关引用的一点.我可以做SQL语句,但我从未使用过引用.

  1. 它们用于什么?
  2. 它们是如何使用的?
  3. 请举个例子

Mar*_*ers 12

REFERENCES关键字是外键约束的一部分,它使MySQL要求引用表的指定列中的值也存在于引用表的指定列中.

这可以防止外键引用不存在或被删除的ID,并且可以选择阻止您在仍然引用行时删除它们.

一个具体示例是,如果每个员工都必须属于某个部门,那么您可以通过employee.departmentid引用添加外键约束department.id.

运行下面的代码来创建两个测试表tableatableb其中列a_idtableb引用的主键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表,否则将忽略约束.