user2492854
user2492854

Reputation: 401

sql create table with foreign key

In my database I need to create a table which has two foreign keys, I am unable to figure out the source of error although I tried .Any body help me in solving this problem. The mysql command I gave to create the table

create table book_vegetable(
  id int NOT NULL AUTO_INCREMENT,
  producer_offer_id int NOT NULL,
  consumer_id int NOT NULL,
  booked_qty varchar,
  PRIMARY KEY(id),
  FOREIGN KEY(producer_offer_id) 
    REFERENCES producer_offer(id),
  FOREIGN KEY(consumer_id) REFERENCES user(id)
);

The error I am getting

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'PRIMARY KEY(id),FOREIGN KEY(producer_offer_id) REFERENCES producer_offer(id),FOR' at line 1

Upvotes: 0

Views: 131

Answers (2)

Gryphius
Gryphius

Reputation: 78886

Your first problem was caused by a missing length specification on the booked_qty varchar column.

The usual suspects for error 150:

  • mismatch in primary vs. foreign key type (for example int - bigint). make sure they match exactly
  • different table engines (for example if you try to reference a MyIsam table in a InnoDB table)

Upvotes: 2

Priit
Priit

Reputation: 31

This works in MySQL, just tested (note that producer offer and user are just a mock tables).

create table producer_offer (id int(10) not null auto_increment, primary key(id));
create table user (id int(10) not null auto_increment, primary key(id));

create table book_vegetable (
    id int(10) NOT NULL AUTO_INCREMENT,
    producer_offer_id int(10) NOT NULL,
    consumer_id int(10) NOT NULL,
    booked_qty varchar(255),
    PRIMARY KEY(id),
    FOREIGN KEY(producer_offer_id) REFERENCES producer_offer(id),
    FOREIGN KEY(consumer_id) REFERENCES user(id)
);

Upvotes: 1

Related Questions