使用外键创建表会显示错误

时间:2012-12-30 10:21:02

标签: mysql sql database foreign-keys

我正在尝试创建一个表并且收到错误,告诉我第9行周围有问题。这是代码。

CREATE TABLE shirts_link (
    adult VARCHAR(1) NOT NULL,
    kids VARCHAR(1) NOT NULL,
    babies VARCHAR(1) NOT NULL,
    shirt_id INT(4) NOT NULL,
    size_id INT(4) NOT NULL,
    price_id INT(4) NOT NULL,
    PRIMARY KEY (shirt_id,size_id,price_id),
    FOREIGN KEY (shirt_id) REFERENCES shirts(id),
    FOREIGN KEY (size_id) REFERENCES shirt_sizes(id),
    FOREIGN KEY (price_id) REFERENCES shirt_prices(id)
    )ENGINE=INNODB;

这是我想要链接到的其他表格。

CREATE TABLE shirts (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY NOT NULL,
    shirt_name VARCHAR(20) NOT NULL,
    men VARCHAR(10) NULL,
    women VARCHAR(10) NULL,
    boys VARCHAR(10) NULL,
    girls VARCHAR(10) NULL,
    babies VARCHAR(10) NULL,
)ENGINE=INNODB;

CREATE TABLE shirt_sizes (
    id INT UNSIGNED AUTO_INCREMENT NOT NULL PRIMARY KEY,
    size_name VARCHAR(10) NOT NULL
)ENGINE=INNODB;

CREATE TABLE shirt_prices (
        id INT UNSIGNED AUTO_INCREMENT NOT NULL PRIMARY KEY,
        price_cat VARCHAR(10) NOT NULL,
        price NUMERIC(6,2) NOT NULL
    )ENGINE=INNODB;

2 个答案:

答案 0 :(得分:5)

问题是您使用单引号包装表名列名。它不应该使用backtick代替

FOREIGN KEY (shirt_id) REFERENCES shirts(id),
FOREIGN KEY (size_id) REFERENCES shirt_sizes(id),
FOREIGN KEY (price_id) REFERENCES shirt_prices(id)

FOREIGN KEY (`shirt_id`) REFERENCES `shirts`(`id`),
FOREIGN KEY (`size_id`) REFERENCES `shirt_sizes`(`id`),
FOREIGN KEY (`price_id`) REFERENCES `shirt_prices`(`id`)

但在这种情况下,它们是可选,因为它们不是MySQL保留的关键字。

更新1

密钥的数据类型必须相同,将这些列声明为UNSIGNED

shirt_id INT(4) UNSIGNED NOT NULL,
size_id INT(4) UNSIGNED NOT NULL,
price_id INT(4) UNSIGNED NOT NULL,

答案 1 :(得分:3)

CREATE TABLE shirts_link (
    adult VARCHAR(1) NOT NULL,
    kids VARCHAR(1) NOT NULL,
    babies VARCHAR(1) NOT NULL,
    shirt_id INT(4) NOT NULL,
    size_id INT(4) NOT NULL,
    price_id INT(4) NOT NULL,
    PRIMARY KEY (shirt_id,size_id,price_id),
    FOREIGN KEY (shirt_id) REFERENCES shirts(id),
    FOREIGN KEY (size_id) REFERENCES shirt_sizes(id),
    FOREIGN KEY (price_id) REFERENCES shirt_prices(id)
    )ENGINE=INNODB;

它在sqlfiddle上为我工作 这是我的代码:

CREATE TABLE shirts(
  id INT NOT NULL,
  PRIMARY KEY (id)
  );
CREATE TABLE shirts_link (
    adult VARCHAR(1) NOT NULL,
    kids VARCHAR(1) NOT NULL,
    babies VARCHAR(1) NOT NULL,
    shirt_id INT(4) NOT NULL,
    size_id INT(4) NOT NULL,
    price_id INT(4) NOT NULL,
    PRIMARY KEY (shirt_id,size_id,price_id),
    FOREIGN KEY (shirt_id) REFERENCES shirts(id)
    );