MySQL foreign key creation failure Solution

Source: Internet
Author: User

Create 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 ')
);

Create another 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 ')
);


You can use the show create table orders statement to query orders Information and find that the foreign key is not created successfully. I checked some information and finally found the reason. Mysql creates a table of the MyISAM type by default. You must specify the table type as innodb:


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 message is displayed:
ERROR 1005 (HY000): Can't create table 'test. orders '(errno: 150)
Set the persons Table type to innodb.

To sum up the following situations:
1. Foreign keys and referenced Foreign keys are of different types, such as integer and double
2. The column to be referenced cannot be found.
3. The character encoding of the table is different.
4. inconsistent data engine types, such as innodb and myisam

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.