Get the App
SLTechnology News&Howtos  ›  Database  › 

How to solve the problem of failed creation of mysql foreign keys

Shulou Source: shulou.com Published: 2022-05-31 18:00:10 10月17日 Update

This article mainly explains "how to solve the problem of mysql foreign key creation failure", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "how to solve the problem of mysql foreign key creation failure" bar!

Create a persons:

CREATE TABLE `persons` (

`id_ p` int (11) NOT NULL AUTO_INCREMENT

`lastname` varchar (10) DEFAULT NULL

`firstname` varchar (10) DEFAULT NULL

`address` varchar (50) DEFAULT NULL

`city` varchar (10) DEFAULT NULL

PRIMARY KEY (`id_ p`)

); www.2cto.com

Re-create table orders:

CREATE TABLE `orders` (

`id_ o` int (11) NOT NULL AUTO_INCREMENT

`orderno` int (11) NOT NULL

`id_ p` int (11) NOT NULL

PRIMARY KEY (`id_ o`)

FOREIGN KEY (`id_ p`) REFERENCES `persons` (`id_ p`)

);

Using the show create table orders statement to query the information of orders, it is found that the foreign key was not created successfully. After checking some information, we finally found out the reason. The table created by mysql by default is of type MyISAM, and the type of the table needs to be specified as innodb:

Www.2cto.com

CREATE TABLE `orders` (

`id_ o` int (11) NOT NULL AUTO_INCREMENT

`orderno` int (11) NOT NULL

`id_ p` int (11) NOT NULL

PRIMARY KEY (`id_ o`)

FOREIGN KEY (`id_ p`) REFERENCES `persons` (`id_ p`)

) ENGINE=InnoDB

However, the following error is prompted at this time:

ERROR 1005 (HY000): Can't create table 'test.orders' (errno: 150)

It is OK to specify the type of persons table as innodb.

Summarize several situations in which foreign key creation failed:

1. Foreign keys are different from referenced foreign keys, such as integer and double

two。 Could not find the column to be referenced

3. The character encoding of the table is different.

4. Data engine types are inconsistent, such as innodb and myisam

Thank you for your reading, the above is the content of "how to solve the problem of failed creation of mysql foreign keys". After the study of this article, I believe you have a deeper understanding of how to solve the problem of failed creation of mysql foreign keys. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Questions types learning content situation consistency success information reasons characters that is engines ideas data articles more knowledge knowledge points articles coding Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple Xiaomi MariaDB vpn Docker