Skip to search.

Breaking News Visit Yahoo! News for the latest.

×Close this window

  1. Home >
  2. All Categories >
  3. Computers & Internet >
  4. Programming & Design >
  5. Resolved Question
Bob Bob
Member since:
May 06, 2009
Total points:
3 (Level 1)

Resolved Question

Show me another »

Cannot add or update a child row: a foreign key constraint fails (`hw2`.`order_item`,?

I'm trying to do an insert into my order_item table, but I'm getting this error. Can someone help with why this is happening. Thank you.

My sql code to create the tables is below.

MySQL Syntax (Toggle Plain Text)

DROP TABLE IF EXISTS order_item, orders, customer, product;

CREATE TABLE customer
( id INT(10) NOT NULL AUTO_INCREMENT,
lastname VARCHAR(25),
firstname VARCHAR(15),
username VARCHAR(25),
password VARCHAR(25),
email VARCHAR(35),
address VARCHAR(35),
city VARCHAR(15),
state CHAR(2),
zip5 CHAR(5),
PRIMARY KEY (id)
) ENGINE = INNODB;


CREATE TABLE product
( id INT(12) NOT NULL AUTO_INCREMENT,
product_name VARCHAR(255),
details TEXT,
price VARCHAR(16),
date_added DATE NOT NULL,
PRIMARY KEY (id)
) ENGINE = INNODB;


CREATE TABLE orders
( id INT(10) NOT NULL AUTO_INCREMENT,
customer INT(10),
order_date DATE NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (customer) REFERENCES customer (id)
) ENGINE = INNODB;

CREATE TABLE order_item
( order_id INT(10),
prod_id INT(12),
qty SMALLINT DEFAULT 1,
FOREIGN KEY (order_id) REFERENCES orders (id)
ON DELETE CASCADE ON UPDATE CASCADE,
FOREIGN KEY (prod_id) REFERENCES product (id),
PRIMARY KEY (order_id, prod_id)
) ENGINE = INNODB;
TheMadProfessor by TheMadPr...
Member since:
March 11, 2008
Total points:
135,120 (Level 7)

Best Answer - Chosen by Voters

Did you do the insert into table 'orders' first? Because of the foreign key constraint, orders.id must be populated before attempting to populate order_item.order_id
100% 1 Vote

There are currently no comments for this question.

Other Answers (0)

No other answers.

Answers International

Yahoo! does not evaluate or guarantee the accuracy of any Yahoo! Answers content. Click here for the Full Disclaimer.

Help us improve Yahoo! Answers. Send Feedback