1

I'm a mysql beginner and I'm currently working on foreign keys. I would like to create three tables: users, items, orders and link them together

Users table:

CREATE TABLE users (
user_id INT(10) UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT,
name VARCHAR(20) NOT NULL,
PRIMARY KEY(user_id)
);

Items table:

CREATE TABLE items (
item_id INT(10) UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT,
name VARCHAR(20) NOT NULL,
PRIMARY KEY(item_id)
);

Orders table:

CREATE TABLE orders (
order_id INT(10) UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT,
item_id INT,
quantity INT(10) NOT NULL,
user_id INT,
PRIMARY KEY (order_id),
FOREIGN KEY (item_id) REFERENCES items (item_id),
FOREIGN KEY (user_id) REFERENCES users (user_id)
);

But I got the error 1005: can't create table 'new.orders' (error:150)

What is wrong with my code?

Thanks!

4

2 に答える 2

5

The data types of the primary table's column and the referencing table's columns must match exactly. In your definitions, items.item_id is INT UNSIGNED, while the foreign key orders.item_id is INT (implicitly SIGNED). The same is true for user_id.

Change the definition as follows, adding UNSIGNED for those two:

CREATE TABLE orders (
  order_id INT(10) UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT,
  item_id INT UNSIGNED,
  quantity INT(10) NOT NULL,
  user_id INT UNSIGNED,
  PRIMARY KEY (order_id),
  FOREIGN KEY (item_id) REFERENCES items (item_id),
  FOREIGN KEY (user_id) REFERENCES users (user_id)
);

It then builds correctly: http://sqlfiddle.com/#!2/cfab8

于 2013-03-02T23:24:11.190 に答える
2

There is no column student_id in items table. Did you mean user_id in users table?

于 2013-03-02T23:17:29.010 に答える