Solution given: ERROR 1005 (HY000): Can not create table 'market.orders' (errno: 150)

1. Describe the problem:

Here I created two tables (customers_info and orders)

Table I: customers_info

CREATE TABLE customers_info
(
c_num INT(11) PRIMARY KEY NOT NULL UNIQUE AUTO_INCREMENT,
c_name VARCHAR(50),
c_contact VARCHAR(50),
c_city VARCHAR(50),
c_birth DATETIME NOT NULL
);

  

 

 

At this point we are in the New Table II orders when the subject of the request c_id data type VARCHAR (50), but he asked me to set up a foreign key constraint, associated to customers_info table c_num.

CREATE TABLE orders 
(
o_num INT(11) PRIMARY KEY NOT NULL UNIQUE AUTO_INCREMENT,
o_date DATE,
c_id VARCHAR(50),
CONSTRAINT fk_c_num FOREIGN KEY(c_id) REFERENCES customers_info(c_num) 
);

  Perform this time, there will be an error: ERROR 1005 (HY000): Can not create table 'market.orders' (errno: 150)

 

The general situation problems arise:

1, the foreign key reference type is not the same as the primary key is a foreign key int char

2, the main column is not found in the referenced table

3, the primary and foreign keys inconsistent character encoding, or it may be different storage engine

Here I encountered the first and third case, as shown:

 

 

Solution:

1. Modify the same two tables storage engine

2. Modify the data types match each

 

 

 

 

MariaDB [market]> show create table customers_info\G
*************************** 1. row ***************************
       Table: customers_info
Create Table: CREATE TABLE `customers_info` (
  `c_num` int(11) NOT NULL AUTO_INCREMENT,
  `c_name` varchar(70) DEFAULT NULL,
  `c_birth` datetime NOT NULL,
  `c_phone` varchar(50) DEFAULT NULL,
  `c_gender` char(1) DEFAULT NULL,
  PRIMARY KEY (`c_num`),
  UNIQUE KEY `c_num` (`c_num`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
1 row in set (0.00 sec)

MariaDB [market]> show create table orders\G
*************************** 1. row ***************************
       Table: orders
Create Table: CREATE TABLE `orders` (
  `o_num` int(11) NOT NULL AUTO_INCREMENT,
  `o_date` date DEFAULT NULL,
  `c_id` int(50) DEFAULT NULL,
  PRIMARY KEY (`o_num`),
  UNIQUE KEY `o_num` (`o_num`),
  KEY `fk_c_num` (`c_id`),
  CONSTRAINT `fk_c_num` FOREIGN KEY (`c_id`) REFERENCES `customers_info` (`c_num`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
1 row in set (0.00 sec)

  

 

Guess you like

Origin www.cnblogs.com/python-wen/p/11545515.html