在Mysql中创建外键有错误无法解析附近的表名

时间:2015-04-30 07:33:01

标签: mysql

我在添加外键时遇到问题。我有以下脚本:

    CREATE DATABASE IF NOT EXISTS dbdemo;
    use dbdemo;

    CREATE TABLE categories(
        cat_id int unsigned not null auto_increment primary key,
        cat_name varchar(255) not null,
        cat_description text
    ) ENGINE=InnoDB;

    CREATE TABLE products(
        prd_id int unsigned not null auto_increment primary key,
        prd_name varchar(355) not null,
        prd_price decimal,
        cat_id int unsigned not null,
        constraint fk_cat
        FOREIGN KEY fk_cat( cat_id )
        REFERENCES categories( cat_id )
        ON UPDATE cascade
        ON DELETE RESTRICT
    ) ENGINE=InnoDB;

    CREATE TABLE vendors(
    vdr_id int unsigned not null auto_increment primary key,
    vdr_name varchar(255)
) ENGINE=InnoDB;

ALTER TABLE products
ADD COLUMN prod_vdr_id int unsigned not null;

然后当我尝试添加FOREIGN KEY时出现错误:

ALTER TABLE products 
ADD FOREIGN KEY fk_vendor(prod_vdr_id)
REFERENCES vendor(vdr_id)
ON UPDATE CASCADE
ON DELETE NO ACTION;

然后我收到了这个错误:

Error Code: 1005. Can't create table 'dbdemo.#sql-565_35' (errno: 150)

如果我运行“Show Engine innodb status”,我得到了:

------------------------
LATEST FOREIGN KEY ERROR
------------------------
150430 15:30:00 Error in foreign key constraint of table dbdemo/#sql-565_35:
FOREIGN KEY fk_vendor(prod_vdr_id)
REFERENCES vendor(vdr_id)
ON UPDATE CASCADE
ON DELETE NO ACTION:
Cannot resolve table name close to:
(vdr_id)
ON UPDATE CASCADE
ON DELETE NO ACTION

有谁可以告诉我哪里出错? TQVM

1 个答案:

答案 0 :(得分:0)

这是供应商而不是供应商<​​/ p>

ALTER TABLE products 
ADD FOREIGN KEY fk_vendor(prod_vdr_id)
REFERENCES vendors(vdr_id)
ON UPDATE CASCADE
ON DELETE NO ACTION;