1

我正在尝试创建一个表,但收到一个错误消息,告诉我第 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;
4

2 回答 2

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,
于 2012-12-30T10:22:35.417 回答
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)
    );
于 2012-12-30T10:25:10.337 回答