为什么仍然可以插入不存在的外键?

use*_*729 4 mysql foreign-keys

mysql>  create table products(id integer unsigned auto_increment primary key);
Query OK, 0 rows affected (0.05 sec)

mysql> CREATE TABLE orders (
    ->     id integer PRIMARY KEY auto_increment,
    ->     product_id integer REFERENCES products (id),
    ->     quantity integer,
    ->     INDEX product_id_idx (product_id)
    -> );
Query OK, 0 rows affected (0.05 sec)
mysql> insert into orders(product_id,quantity) value(1,1);
Query OK, 1 row affected (0.00 sec)
Run Code Online (Sandbox Code Playgroud)

由于产品 1 不存在,该insert语句应该会失败,但实际上不会。

为什么?

Ike*_*ker 5

您应该在列定义下方显式定义外键。

您还应该使 product_id 无符号,因为父密钥是无符号的:

CREATE TABLE orders (
  id integer PRIMARY KEY auto_increment,
  product_id integer unsigned,
  quantity integer,
  INDEX product_id_idx (product_id),
  CONSTRAINT FK_ORDER_TO_PRODUCT FOREIGN KEY (product_id) REFERENCES products (id)
 ) engine=innodb;
Run Code Online (Sandbox Code Playgroud)