FOREIGN KEY

 

什麼是 FOREIGN KEY:

A FOREIGN KEY in one table points to a PRIMARY KEY in another table.

作用:

prevent actions that would destroy links between tables.

建立:

那會 ref Table: Group 內的 gid column

CREATE TABLE User
(
    ....................
    uid int,
    gid int,
    PRIMARY KEY (uid),
    FOREIGN KEY (gid) REFERENCES Group(gid)
)

 


清有 FOREIGN_KEY 的 Tables

error:

ERROR 1701 (42000) at line 1: Cannot truncate a table referenced in a foreign key constraint 
(`roundcube`.`cache`, CONSTRAINT `user_id_fk_cache` FOREIGN KEY (`user_id`) REFERENCES `roundcube`.`users` (`user_id`))

解決:

SET FOREIGN_KEY_CHECKS = 0;

SHOW Variables WHERE Variable_name='foreign_key_checks';

TRUNCATE table1;

SET FOREIGN_KEY_CHECKS = 1;