-1

I am trying to execute this query:

create table order_details(
    Order_id int PRIMARY KEY AUTO_INCREMENT,
    Book_Id int, 
    Cust_Name varchar(50),
    Phone_No int,
    Address varchar(100),
    Order_Date DATE,
    Quantity int,
    FOREIGN KEY(Book_Id) REFERENCES book(Book_Id));

But the result is a MySQL Error 1005:

ERROR 1005 (HY000): Can't create table 'bookstore.order_details' (errno: 150)
DrakaSAN
  • 7,673
  • 7
  • 52
  • 94
Jeet Patel
  • 1,140
  • 18
  • 51

2 Answers2

1
create table order_details(
   Order_id int PRIMARY KEY AUTO_INCREMENT,
   Book_Id int, 
   Cust_Name varchar(50),
   Phone_No int,
   Address varchar(100),
   Order_Date DATE,
   Quantity int,
FOREIGN KEY(Book_Id) REFERENCES book(Book_Id));

Error (150) is being thrown because mysql is unable to reference the specified foreign key. This can be caused for a number of reasons however, I recommend taking the following steps to troubleshoot this.

A common issue that causes this error to become evasive is when you have not performed USE my_database_name; before executing the query. It fails because the context is either wrong or absent.

1.) Revise your query by adding in the name of the database in the reference

  • Example: FOREIGN KEY(`Book_Id`) REFERENCES `my_database_name`.`book`(`Book_Id`));

2.) Take a look at the book table and make sure `Book_Id` is the correct type (int) and is named exactly as you reference it. Perform the following queries and you may find your answer:

  • SELECT `b`.`Book_Id` FROM `book` AS `b`;
  • EXPLAIN `book`;

Selecting Book_Id from the referenced table will rule out typos in field naming. Explain will reveal the value type & key information that should help ensure consistency between foreign relations when investigating issues like this.

Timothy Wood
  • 487
  • 3
  • 10
0

You might not be having a 'book' table in your database or if you have one then there might not be a column named 'Book_id'

Chayan Bansal
  • 1,857
  • 1
  • 13
  • 23