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)
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.
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'
Related
I was about to create two tables (1st table: fooditem_tbl & 2nd table: orderitem_tbl). I was planning to create 2 foreign keys (ITEM_NAME,UNIT_PRICE) on the 2nd table. I wasn't able to run the query of the 2nd table(orderitem_tbl), due to an error which is near at "INDEX". I kept looking at my query, and I still don't know what's the cause of the error.
My first table , this one works
CREATE TABLE FOODITEM_TBL
(ITEM_ID INT AUTO_INCREMENT,
ITEM_NAME VARCHAR(50) UNIQUE,
UNIT_PRICE DOUBLE UNSIGNED,
ITEM_QUANTITY INT UNSIGNED,
IN_STOCK BOOLEAN,
PRIMARY KEY (ITEM_ID, ITEM_NAME, UNIT_PRICE));
The 2nd table, which is below fails to create
CREATE TABLE ORDERITEM_TBL(
ORDER_ID INT AUTO_INCREMENT,
ITEM_NAME VARCHAR(50) UNIQUE,
UNIT_PRICE DOUBLE UNSIGNED,
ITEM_QUANTITY INT UNSIGNED,
CUSTOMER_NAME VARCHAR(50),
ADDRESS VARCHAR(50),
CONTACT_NUMBER VARCHAR(50),
PRIMARY KEY (ORDER_ID),
INDEX (ITEM_NAME,UNIT_PRICE),
FOREIGN KEY (ITEM_NAME,UNIT_PRICE) REFERENCES
FOODITEM_TBL(ITEM_NAME,UNIT_PRICE)
) ENGINE = InnoDB;
P.S Please help
Q: What is causing the error? How can I fix it?
For InnoDB, there must be an index on the target table, on the target column(s). Datatypes of the referencing foreign key column(s) must match the datatypes of the target column(s).
Before creating the foreign key constraint, make sure a suitable index exists on the target table, e.g.
CREATE UNIQUE INDEX `FOODITEM_TBL_UX3` ON `FOODITEM_TBL` (`ITEM_NAME`, `UNIT_PRICE`) ;
Given that ITEM_NAME is unique in the target table, we know that the combination of ITEM_NAME and UNIT_PRICE will also be unique. I'm not sure why we wouldn't just define a foreign key constraint on just ITEM_NAME, but that doesn't really address the question that was asked.
Personally, I would avoid floating point datatypes (e.g. DOUBLE) for columns involved in foreign key constraints.
When I try to create the 'Project table I get this error Code: 1824. Failed to open the referenced table 'Employee'.
My syntax:
CREATE DATABASE IF NOT EXISTS Test;
USE Test;
CREATE TABLE IF NOT EXISTS Customer (
CustomerID VARCHAR(7) NOT NULL,
CustomerName VARCHAR(50),
CustAdress VARCHAR(70),
CustEmail VARCHAR(50),
PRIMARY KEY (CustomerID)
);
CREATE TABLE IF NOT EXISTS Employee (
EmpID VARCHAR(7) NOT NULL,
EmpName VARCHAR(50),
Position VARCHAR(30),
EmpTimePrice INT(4),
PRIMARY KEY (EmpID)
);
CREATE TABLE IF NOT EXISTS Project (
ProjectNo VARCHAR(7),
ProjectName VARCHAR(50),
StartDate DATE,
ProjTimePrice INT(6),
CustomerID VARCHAR(7),
EmpID VARCHAR(7),
PRIMARY KEY (ProjectNo),
FOREIGN KEY (EmpID) REFERENCES Employee (EmpID),
FOREIGN KEY (CustomerID) REFERENCES Customer (CustomerID)
);
CREATE TABLE IF NOT EXISTS ProjectWork (
ProjectNo VARCHAR(7),
EmpID VARCHAR(7),
PWDATE DATE,
HoursWorked INT(5),
FOREIGN KEY (ProjectNo) REFERENCES Project (ProjectNo),
FOREIGN KEY (EmpID) REFERENCES Employee (EmpID)
);
The names look correct to me and I have referenced the foreign key so I don't understand why I get this error. Any help would be appreciated, thanks.
This normally happens when the two tables have different Table engines. so check both tables if they have same table engines. for example MYISAM do not support Foreign Keys
Just edited EmpID to empID and it worked for some reason.
One of the easiest ways to get this error is referencing a table that doesn't exist yet. Eg if you run the following code on a new schema:
create table ttest (bob varchar(10) not null,
constraint fkbob foreign key (bob) references other(bob) );
... you will get the MySQL error:
Error Code: 1824. Failed to open the referenced table 'other'
Because the other table doesn't exist.
The code in the question above creates Employee before referencing it. However, note that the CREATE DATABASE and CREATE TABLE statements have IF EXISTS, but there are no DROP IF EXISTS statements, as when creating a new database. If you were debugging a table creation script, changing and fixing things as you go, it would have been pretty easy to get into an inconsistent state where the tables were out of synch with the code. This would also explain why other people could run the code cleanly, because these tables didn't exist in their schema yet.
I am relatively new to the database world so bear with me. I'm just trying to add foreign key constraints and I keep getting error 1215 "cannot add foreign key constraint".
CREATE TABLE InProcessSamples
(
SampleNumber Int(6),
WorkOrder Int(8),
DueDate Date,
BeginsTesting Date,
FinishedTesting Date,
CONSTRAINT fk_sample_number FOREIGN KEY(SampleNumber) REFERENCES AllRecords(SampleNumber),
CONSTRAINT fk_work_order FOREIGN KEY(WorkOrder) REFERENCES SamplesReceived(WorkOrder)
);
CREATE TABLE SamplesReceived
(
WorkOrder Int(8) PRIMARY KEY,
SampleNumber Int(6),
RecTimeStamp DateTime,
PartNumber Int(10),
Description Char(36),
CONSTRAINT fk_sample_number FOREIGN KEY(SampleNumber) REFERENCES AllRecords(SampleNumber),
CONSTRAINT fk_part_number FOREIGN KEY(PartNumber) REFERENCES PartNumbers(PartNumber)
);
CREATE TABLE AllRecords
(
SampleNumber Int(6) PRIMARY KEY,
WorkOrder Int(8),
DueDate Date,
BeginsTesting Date,
FinishedTesting Date,
RecTimeStamp DateTime,
MeasurementOne Double,
MeasurementTwo Double,
PassDielectric Char(3),
PassedAllTest Char(3),
CONSTRAINT fk_work_order FOREIGN KEY(WorkOrder) REFERENCES SamplesReceived(WorkOrder),
CONSTRAINT fk_part_number FOREIGN KEY(PartNumber) REFERENCES PartNumbers(PartNumber)
);
CREATE TABLE PartNumbers
(
PartNumber Int(10) PRIMARY KEY,
Description Char(36)
);
Regardless of whether your design is off or not, you can't declare a foreign key reference to a table you haven't created yet.
CREATE TABLE statements are evaluated in order from top to bottom of your SQL script. As MySQL is trying to create the first table, the second and third tables don't exist yet. So there's nothing for the foreign keys to reference.
You should create tables in an order that allows the referenced table to exist before you create the table that has the foreign key to reference it. In this case, you have a circular dependency, so the only way to do it is to create either SamplesReceived or AllRecords without one of its foreign keys, and then go back afterward and add that foreign key.
CREATE TABLE PartNumbers, because it's needed by SamplesReceived and AllRecords
CREATE TABLE SamplesReceived, because it's needed by InProcessSamples and AllRecords
CREATE TABLE AllRecords, because it's needed by InProcessSamples
ALTER TABLE SamplesReceived ADD FOREIGN KEY(SampleNumber) REFERENCES AllRecords(SampleNumber);
CREATE TABLE InProcessSamples
That's if the circular reference is really needed.
But as other folks have answered, perhaps your circular reference isn't really a good design.
The circular reference could be needed; what it does in your case is enforce that for every row in SamplesReceived, you must have a matching row in AllRecords, and vice-versa, every row in AllRecords must have a matching row in SamplesReceived.
I don't know why that's important in your application. It might be, but you haven't told us anything about the workflow you're trying to model so I can't tell.
the normalization is all wrong:
this one is good:
Part
---------------
Part_id
Description
then you have redundancies and other issues everywhere...
maybe start with this:
WorkOrder
-------------
workorder_id
Sample
----------
sample_id
workorder_id
part_id
Test
--------------
test_id
description
min_passing_value
max_passing_value
TestResult
---------------
testresult_id
test_id
description
result_value
test_date
sample_id
although this is a repeated question,
I have been searching through most of the similar posts, but found nothing useful.
Here's my SQL script for MySQL.
CREATE DATABASE IF NOT EXISTS store;
USE store;
CREATE TABLE IF NOT EXISTS Box (
coord VARCHAR (255),
box_id INT UNSIGNED NOT NULL,
img_path VARCHAR (256),
PRIMARY KEY (coord, box_id)
);
CREATE TABLE IF NOT EXISTS Tool (
serial VARCHAR (50),
tool_id INT,
descr VARCHAR (256),
box_id INT UNSIGNED NOT NULL,
tool_state BOOLEAN,
PRIMARY KEY (tool_id),
FOREIGN KEY (box_id) REFERENCES Box(box_id)
);
Output is: ERROR 1005 (HY000) at line 9: Can't create table 'store.Tool' (errno: 150)
Any suggestion
From: http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html
If you re-create a table that was dropped, it must have a definition
that conforms to the foreign key constraints referencing it.It must
have the right column names and types, and it must have indexes on the
referenced keys, as stated earlier. If these are not satisfied, MySQL
returns error number 1005 and refers to error 150 in the error
message.
I guess you have to use the same amount of foreign key, in your code you use 2 PK in table Box, so either you use only box_id as your PK or add foreign key to table Tool..
Here is my SQL script
CREATE TABLE tracks(
track_id int NOT NULL AUTO_INCREMENT,
account_id int,
track_name varchar(255),
track_path varchar(255),
track_art_path varchar(255),
track_desc text,
primary key(track_id),
FOREIGN KEY (account_id) REFERENCES accounts_profile(accnt_id)
)
I don't see any syntax errors. Everything looks fine. My Database Engine is innoDB. but how come I keep on receiving this error?
#1005 - Can't create table 'beatbeast.tracks' (errno: 150)
It's not showing what line where the error is.
Errno 150 is generally the result of a mismatch between the exact data types of the main table's referenced column, and the referencing column. In your case, tracks.account_id is a signed INT, but the column it references accounts_profile.accnt_id is INT UNSIGNED. So you must create the tracks table using INT UNSIGNED for account_id as well:
CREATE TABLE tracks(
track_id int NOT NULL AUTO_INCREMENT,
account_id int UNSIGNED,
track_name varchar(255),
track_path varchar(255),
track_art_path varchar(255),
track_desc text,
primary key(track_id),
FOREIGN KEY (account_id) REFERENCES accounts_profile(accnt_id)
)
From the documentation:
If MySQL reports an error number 1005 from a CREATE TABLE statement,
and the error message refers to error 150, table creation failed
because a foreign key constraint was not correctly formed.
Check that the datatype of accounts_profile.accnt_id matches tracks.account_id exactly. Currently one is an int, so the other must also be an int.
Furhter, the documentation suggests to call:
SHOW ENGINE INNODB STATUS
after you get the error message for a more detailed explanation.