Here is a simple example that relates
parent and child tables through a single-column foreign key:CREATE TABLE parent (id INT NOT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE child (id INT, parent_id INT,
INDEX par_ind (parent_id),
FOREIGN KEY (parent_id) REFERENCES parent(id)
ON DELETE CASCADE
) ENGINE=INNODB;A more complex example in which a
product_order table has foreign keys for two other tables. One foreign key references a two-column index in the product table. The other references a single-column index in the customertable:CREATE TABLE product (category INT NOT NULL, id INT NOT NULL,
price DECIMAL,
PRIMARY KEY(category, id)) ENGINE=INNODB;
CREATE TABLE customer (id INT NOT NULL,
PRIMARY KEY (id)) ENGINE=INNODB;
CREATE TABLE product_order (no INT NOT NULL AUTO_INCREMENT,
product_category INT NOT NULL,
product_id INT NOT NULL,
customer_id INT NOT NULL,
PRIMARY KEY(no),
INDEX (product_category, product_id),
FOREIGN KEY (product_category, product_id)
REFERENCES product(category, id)
ON UPDATE CASCADE ON DELETE RESTRICT,
INDEX (customer_id),
FOREIGN KEY (customer_id)
REFERENCES customer(id)) ENGINE=INNODB;InnoDB enables you to add a new foreign key constraint to a table by using ALTER TABLE:ALTER TABLE tbl_name
ADD [CONSTRAINT [symbol]] FOREIGN KEY
[index_name] (index_col_name, ...)
REFERENCES tbl_name (index_col_name,...)
[ON DELETE reference_option]
[ON UPDATE reference_option]The foreign key can be self referential (referring to the same table). When you add a foreign key constraint to a table using
ALTER TABLE, remember to create the required indexes first.Foreign Keys and ALTER TABLE
InnoDB supports the use of ALTER TABLE to drop foreign keys:ALTER TABLE tbl_name DROP FOREIGN KEY fk_symbol;Identify Foreign Key Creation Failure
If MySQL reports an error number 1005 from a CREATE TABLE statement, and the error message refers to error 150, table creation failed because a foreign key constraint was not correctly formed.
No comments:
Post a Comment