Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Two methods of setting Foreign key to mysql Database

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

Here are two ways to set foreign keys to a mysql database. The secret of the text is to be close to the topic. So, no gossip, let's just read the following, I believe that after reading the two ways to set foreign keys to the mysql database this article will certainly benefit you.

1. Actions when creating a table

Class table (master table):

Create table tb1 (id INT PRIMARY KEY AUTO_INCREMENT, classname VARCHAR (20) NOT NULL)

User table (child table):

Create table tb2 (id INT PRIMARY KEY AUTO_INCREMENT, username VARCHAR (20) NOT NULL, classid INT, FOREIGN KEY (classid) REFERENCES tb1 (id) ON DELETE CASCADE ON UPDATE CASCADE)

2. Add foreign keys to the existing tables

ALTER TABLE tb3 ADD CONSTRAINT tipped C FOREIGN KEY (classid) REFERENCES tb1 (id)

After that, you can use the command to view the operation of creating the table, and SHOW CREATE TABLE tb2; can find this sentence in it.

PRIMARY KEY (`id`), KEY `classid` (`classid`), CONSTRAINT `tb2_ibfk_ 1` FOREIGN KEY (`classid`) REFERENCES `tb1` (`id`) ON DELETE CASCADE

Indicates that the foreign key has been created successfully.

Additional instructions are attached:

CASCADE: deletes or updates from the parent table and automatically deletes or updates matching rows in the child table.

SET NULL: delete or update rows from the parent table and set the foreign key column NULL in the child table. The premise is to ensure that the foreign key column is not NOT NULL.

RESTRICT: rejects delete or update operations on the parent table.

Is there anything you don't understand about the above two methods of setting foreign keys to the mysql database? Or if you want to know more about it, you can continue to follow our industry information section.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report