简体   繁体   English

sql用外键创建表

[英]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 我给创建表的mysql命令

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; 您的SQL语法有误; 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 请在第1行的'PRIMARY KEY(id),FOREIGN KEY(producer_offer_id)REFERENCES producer_offer(id),FOR'附近检查与您的MySQL服务器版本相对应的手册以使用正确的语法

Your first problem was caused by a missing length specification on the booked_qty varchar column. 您的第一个问题是由于booked_qty varchar列上的长度规范丢失。

The usual suspects for error 150: 常见错误150:

  • mismatch in primary vs. foreign key type (for example int - bigint). 主键与外键类型不匹配(例如int-bigint)。 make sure they match exactly 确保它们完全匹配
  • different table engines (for example if you try to reference a MyIsam table in a InnoDB table) 不同的表引擎(例如,如果您尝试在InnoDB表中引用MyIsam表)

This works in MySQL, just tested (note that producer offer and user are just a mock tables). 这在刚刚经过测试的MySQL中有效(请注意,生产者报价和用户只是一个模拟表)。

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)
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM