MySQL foreign key (FOREIGN key)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.