MySQL cannot delete Foreign keys

Source: Internet
Author: User

1. What is referential integrity?
-------
Integrity of reference (integrity constraints) is an important concept in database design. When a table in the database is associated with one or more tables, the integrity of reference is involved. For example:
Document category table-categories
Category_id name
1. SQL Server
2 Oracle
3 PostgreSQL
5 SQLite

Article table-Articles
Article_id category_id title
1 1 aa
2 2 bb
3 4 cc

The preceding two tables use category_id. The categories table has four records and the articles table has three records.

However, for some reason, we may have deleted the records whose category_id is 4 in the categories table, but the articles table still has a record whose category_id is 4. Obviously, this record with category_id = 4 should not exist in the articles table, which can easily cause data disorder.

On the contrary, the foreign key relationship (foreign key relationships) discusses the relationship between the parent table (categories) and the sub-table (articles) by introducing the foreign key (foreign key) this concept ensures referential integrity, which makes the database quite simple. For example, to delete the category_id = 4 record in the categories table and delete all records in the category_id = 4 in the articles table, if the foreign key is not introduced, we must execute two SQL statements; if there is a foreign key, you can easily use an SQL statement to meet the requirements.

2. Conditions for using foreign keys
------
MySQL only introduces Foreign keys after v3.23.34, so do not think about the previous versions :). In addition, you must meet the following conditions:

1) Open InnoDB Engine Support in my. CNF configuration file.
# Uncomment the following if you are using InnoDB tables
Innodb_data_home_dir =/var/DB/MySQL/
Innodb_data_file_path = ibdata1: 10 m: autoextend
Innodb_log_group_home_dir =/var/DB/MySQL/
Innodb_log_arch_dir =/var/DB/MySQL/

2) All associated tables must use the InnoDB engine.

3) All associated fields must be created.
MySQL v4.0 and later versions are automatically created when defining foreign keys. Therefore, you must manually define indexes before v4.0 (including v4.0.

4) The associated fields must adopt similar data types or convertible data types. Of course, it is best to use the same types.
For example, if the field in the parent table is of the tinyint type, the child table can only use tinyint, smallint, Int, bigint, and other types.

3. Foreign key syntax reference
-----
You can use create table or alter table to define foreign keys.
Create Table Syntax:
Create [temporary] Table [if not exists] tbl_name
[(Create_definition,…)]

Create_definition:
Column_definition
| [Constraint [Symbol] foreign key [index_name] (index_col_name ,...) [Reference_definition]

Column_definition:
Col_name type [not null | null] [Default default_value]
[Auto_increment] [unique [Key] | [primary] Key]
[Comment 'string'] [reference_definition]

Index_col_name:
Col_name [(length)] [ASC | DESC]

Reference_definition:
References tbl_name [(index_col_name,…)]
[Match full | match partial | match simple]
[On Delete reference_option]
[On update reference_option]

Reference_option:
Restrict | cascade | set null | no action

Alter table Syntax:
Alter [ignore] Table tbl_name
Alter_specification [, alter_specification]…

Alter_specification:
| Add [constraint [Symbol] primary key [index_type] (index_col_name ,...)
| Add [constraint [Symbol] unique [Index] [index_name] [index_type] (index_col_name ,...)
| Add [constraint [Symbol] foreign key [index_name] (index_col_name ,...) [Reference_definition]
| Drop foreign key fk_symbol

4. Define Foreign keys
----
Mysql>Create Table categories (
-> Category_id tinyint (3) unsigned not null auto_increment,
-> Name varchar (30) not null,
-> Primary Key (category_id)
->) Engine = InnoDB;
Query OK, 0 rows affected (0.36 Sec)

Mysql>Insert into categories values (1, 'SQL Server'), (2, 'oracle'), (3, 'postgresql '), (4, 'mysql'), (5, 'sqlite ');
Query OK, 5 rows affected (0.48 Sec)
Records: 5 duplicates: 0 Warnings: 0

Mysql>Create Table members (
-> Member_id int (11) unsigned not null,
-> Name varchar (20) not null,
-> Primary Key (member_id)
->) Engine = InnoDB;

Query OK, 0 rows affected (0.55 Sec)

Mysql>Insert into members values (1, 'test'), (2, 'admin ');
Query OK, 2 rows affected (0.44 Sec)
Records: 2 duplicates: 0 Warnings: 0

Mysql>Create Table articles (
-> Article_id int (11) unsigned not null auto_increment,
-& Gt; Title varchar (255) not null,
-> Category_id tinyint (3) unsigned not null,
-> Member_id int (11) unsigned not null,
-> Index (category_id ),
-> Foreign key (category_id) References categories (category_id ),
-> Constraint fk_member foreign key (member_id) References members (member_id ),
-> Primary Key (article_id)
->) Engine = InnoDB;

Query OK, 0 rows affected (0.63 Sec)

Note: For non-InnoDB tables, the foreign key clause is ignored.
If the following error occurs:
Error 1005: Can't create table './test/articles. frm' (errno: 150)
Check the following definition statements carefully. Common Errors are that the table type is not InnoDB, related fields are written incorrectly, and indexes are missing.

So far categories. category_id and articles. category_id and members. member_id and articles. member_id has a foreign key relationship, only articles. the value of category_id exists with categories. in the category_id table, and articles. the value of member_id exists with members. in the member_id table, data can be inserted or modified. For example:

Mysql>Insert into articles (category_id, member_id, title) values (6, 1, 'foo ');
Error 1452 (23000): cannot add or update a child row: A foreign key constraint fails ('test/articles ', constraint 'articles _ ibfk_1 'foreign key ('category _ id') References 'category' ('id '))

Mysql>Insert into articles (category_id, member_id, title) values (3, 3, 'foo ');
Error 1452 (23000): cannot add or update a child row: A foreign key constraint fails ('test/articles ', constraint 'fk _ member' foreign key ('Member _ id') References 'members '('Member _ id '))

It can be seen that the above two statements will have errors, because in the categories table there is no category_id = 6, members table also does not have a member_id = 3 record, so you cannot insert. The following SQL statement can be used.

Mysql>Insert into articles (category_id, member_id, title) values (3, 2, 'bar ');
Query OK, 1 row affected (0.03 Sec)

5. Delete foreign key definitions
-----
I wonder if you have found that the foreign key articles. member_id has one more constraint fk_member than the articles. category_id clause when defining a foreign key?
This fk_member is used to delete the foreign key definition, as shown below:
Mysql>Alter table articles drop foreign key fk_member;
Query OK, 1 row affected (0.25 Sec)
Records: 1 duplicates: 0 Warnings: 0

In this way, the foreign key definition of articles. member_id is deleted, but how can I delete it if the constraint fk_symbol (that is, the foreign key symbol) is not specified during the definition? Don't worry. MySQL will create one by itself, but you can run the following command to view it:

Mysql>Show create table articles;
+ ---- + ------------ +
| Table | create table |
+ ---- + ------------ +
| Articles | create table 'articles '(
'Article _ id' int (11) unsigned not null auto_increment,
'Category _ id' tinyint (3) unsigned not null,
'Member _ id' int (11) unsigned not null,
'Title' varchar (255) not null,
Primary Key ('Article _ id '),
Key 'category _ id' ('category _ id '),
Key 'Member _ id' ('Member _ id '),
Constraint 'articles _ ibfk_1 'foreign key ('category _ id') References 'category' ('id ')
) Engine = InnoDB default charset = Latin1 |
+ ---- + ------------ +
1 row in SET (0.01 Sec)

We can see that the foreign key symbol of articles. category_id is articles_ibfk_1, because you can run the following command to delete the foreign key definition:

Mysql>Alter table articles drop foreign key articles_ibfk_1;
Query OK, 1 row affected (0.66 Sec)
Records: 1 duplicates: 0 Warnings: 0

6. Summary
---
The disadvantage of the introduction of foreign keys is that the speed and performance will decrease. Of course, foreign keys have many advantages. This article only discusses how to define and delete Foreign keys. The practical application of foreign keys will be introduced in future articles.

 

Related Article

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.