简体   繁体   中英

MySQL Error “Can't create table” Foreign Key Constraint

I'm trying to create a database using MySQL and having difficulties with my code. I created the base table with one attribute that I plan on using as a foreign key in another table but an error message comes up saying I cannot create the table. I only want help with creating that table as I know how to insert data.

    create database aerogames_table;

CREATE TABLE
    O_DETAILS
    (
        B_Number INT NOT NULL,
        B_Name VARCHAR(60) NOT NULL,
        Order_ID INT NOT NULL,
        Order_CName VARCHAR(50) NOT NULL
    )
    engine=innodb;

CREATE TABLE
    P_DETAILS
    (
        PRO_ID INT NOT NULL PRIMARY KEY,
        Order_ID INT NOT NULL,
        CONSTRAINT fk_OrdID_this FOREIGN KEY (Order_ID) REFERENCES O_DETAILS(Order_ID),
        PRO_Seller VARCHAR (50) NOT NULL,
        PRO_Name VARCHAR (50) NOT NULL,
        PRO_Year INT NOT NULL,
        PRO_Price INT NOT NULL
    )
    engine=innodb;

1005 - Can't create table 'aerogames_table.p_details' (errno: 150)

Due to this https://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html

    [CONSTRAINT [symbol]] 
        FOREIGN KEY [index_name] (index_col_name, ...)
        REFERENCES tbl_name (index_col_name,...)

Foreign key need to reference to index column (no need to be primary key) so you need to create index on O_DETAILS.Order_ID like this

    CREATE TABLE
        O_DETAILS
        (
            B_Number INT NOT NULL,
            B_Name VARCHAR(60) NOT NULL,
            Order_ID INT NOT NULL,
            Order_CName VARCHAR(50) NOT NULL,
                    KEY (Order_ID)
        )
        engine=innodb;

    CREATE TABLE
        P_DETAILS
        (
            PRO_ID INT NOT NULL PRIMARY KEY,
            Order_ID INT NOT NULL,
            CONSTRAINT fk_OrdID_this FOREIGN KEY (Order_ID) REFERENCES O_DETAILS(Order_ID),
            PRO_Seller VARCHAR (50) NOT NULL,
            PRO_Name VARCHAR (50) NOT NULL,
            PRO_Year INT NOT NULL,
            PRO_Price INT NOT NULL
        )
        engine=innodb;

Certainly if you make O_DETAILS.Order_ID to be primary key, it will also create for you and this works

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM