聘我网

新概念招聘3.0

为何外键限制没起作用?

vote up0vote downstar
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)
 

1 个答复

vote up0vote downcheck

对于外键,

The size and sign of integer types must be the same

products.idunsigned,而orders.product_id不是。需要统一起来。

foreign key只有InnoDB支持,而MySQL的默认engineMyISAM,所以必须指定。

另外虽然Inline REFERENCES属于SQL标准,但是MySQL目前并不支持或无法识别。

综合上述3点,要改成如下:

CREATE TABLE products (
     id integer unsigned auto_increment primary key
) ENGINE=INNODB;

CREATE TABLE orders (
     id integer PRIMARY KEY auto_increment,
     product_id integer unsigned,
     quantity integer,
     INDEX product_id_idx (product_id),
     FOREIGN KEY (product_id) REFERENCES products (id)
) ENGINE=INNODB;
链接

您的回答





不是您要找的问题? 浏览其他含有标签 的问题或者 自己问个.