由于外键错误无法创建表

时间:2016-03-18 15:35:31

标签: mysql sql

我正在尝试使用其中的产品创建数据库,并且我创建了一个加入产品和商店的表,但是我的“CREATE TABLE”句子不起作用,我得到150错误,150错误,我在不同的网站上搜索过,检查了案例,类型,没有任何作用。

这是代码

CREATE TABLE IF NOT EXISTS `products` (
  `barcode` bigint(20) NOT NULL,
  `name` varchar(32) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT 'Unnamed product',
  `allerg` varchar(32) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT 'z',
  `description` text CHARACTER SET utf8 COLLATE utf8_bin,
  CONSTRAINT pk_products PRIMARY KEY (`barcode`)
)

CREATE TABLE IF NOT EXISTS `stores` (
  `name` varchar(32) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT 'Unnamed store',
  `city` varchar(32) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT 'Not specified',
    `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
    CONSTRAINT pk_stores PRIMARY KEY (`id`)
)

CREATE TABLE IF NOT EXISTS `contain` (
    `barcode` bigint(20) NOT NULL,
    `id` bigint(20) unsigned NOT NULL,  
    CONSTRAINT pk_barcode PRIMARY KEY (`barcode`,`id`),
    CONSTRAINT fk_bc FOREIGN KEY (`barcode`) 
    REFERENCES `products`(`barcode`) ON DELETE CASCADE ON UPDATE CASCADE,   
    CONSTRAINT fk_id FOREIGN KEY (`id`) 
    REFERENCES `stores`(`id`) ON DELETE CASCADE ON UPDATE CASCADE
)

有人看到了吗?

谢谢。

1 个答案:

答案 0 :(得分:1)

CREATE TABLE IF NOT EXISTS `products` (
  `barcode` bigint(20) NOT NULL,
  `name` varchar(32) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT 'Unnamed product',
  `allerg` varchar(32) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT 'z',
  `description` text CHARACTER SET utf8 COLLATE utf8_bin,
  CONSTRAINT pk_products PRIMARY KEY (`barcode`)
);

CREATE TABLE IF NOT EXISTS `stores` (
  `name` varchar(32) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT 'Unnamed store',
  `city` varchar(32) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT 'Not specified',
    `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
    CONSTRAINT pk_stores PRIMARY KEY (`id`)
);

CREATE TABLE IF NOT EXISTS `contain` (
    `barcode` bigint(20) NOT NULL,
    `id` bigint(20) unsigned NOT NULL,  
    CONSTRAINT pk_barcode PRIMARY KEY (`barcode`,`id`),
    CONSTRAINT fk_bc FOREIGN KEY (`barcode`) 
    REFERENCES `products`(`barcode`) ON DELETE CASCADE ON UPDATE CASCADE,   
    CONSTRAINT fk_id FOREIGN KEY (`id`) 
    REFERENCES `stores`(`id`) ON DELETE CASCADE ON UPDATE CASCADE
);