views:

72

answers:

2
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)

Since product 1 doesn't exist,the insert statement is supposed to fail,but in fact not.

Why?

+1  A: 

Foreign keys are only supported when MySQL uses the InnoDB storage engine.

MySQL uses MyISAM as the default storage engine, where foreign key constraints and are simply ignored.

Try your example with the following tables:

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;

Also make sure that the referencing and referenced columns are of the exact same datatype.

Daniel Vassallo
This seems correct from http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html
astander
@astander: Thanks for the external source. I was looking for it :)
Daniel Vassallo
I tried the updated version,still not working,@Ike Walker's answer works,but don't know the reason yet.
Make sure that the referencing and referenced columns are of the exact same datatype. In your original example you had the referenced column set as an unsigned integer, while the referencing column was a normal integer.
Daniel Vassallo
The data types need to be specified the same for both fields for the foreign key to apply.. unsigned is required to indicate "unsigned"
Cez
+4  A: 

You should explicitly define the foreign key below the column definitions.

You should also make product_id unsigned since the parent key is unsigned:

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;
Ike Walker
Why is `unsigned` necessary for `product_id` while the `id` is `signed`
products.id = unsigned integerorders.products_id should therefore be an unsigned integer.inserting into this table would produce:ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails
Cez
This is documented, but _very_ badly:http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html(search for "inline REFERENCES specifications")
Andrew Duffy