Each of the two fields that are foreign keys must be primary keys
Two tables must be a InnoDB table,MyISAM table temporarily does not support foreign keys
The columns of the two tables of the foreign key relationship must be of similar data types, that is, columns that can be converted to each other, such as int and tinyint , and an int and char are not allowed;
The benefits of foreign keys: You can associate two tables, ensure data consistency, and implement cascade operations.
How to create a foreign key:
Example:
1. ALTER TABLE tb_active add constraint fk_id foreign key (user_id) REFERENCES tb_user (ID);
2.
CREATE TABLE `tb_active` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`content` text CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`user_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`),
KEY `user_id_2` (`user_id`),
CONSTRAINT `FK_ID` FOREIGN KEY (`user_id`) REFERENCES `tb_user` (`id`) On Delete Cascade
) ENGINE=InnoDB DEFAULT CHARSET=latin1
关键字 含义
CASCADE 删除包含与已删除键值有参照关系的所有记录
SET NULL 修改包含与已删除键值有参照关系的所有记录,使用NULL值替换(只能用于已标记为NOT NULL的字段)
RESTRICT 拒绝删除要求,直到使用删除键值的辅助表被手工删除,并且没有参照时(这是默认设置,也是最安全的设置)
NO ACTION 啥也不做
MySQL foreign key (FOREIGN key)