尝试使用外键制作表时出现错误

时间:2019-01-31 06:57:50

标签: mysql mysqli

我正在制作一个简单的3表数据库。但是,当我尝试制作prod_owners表时,我总是收到错误消息。我不明白为什么。我尝试在w3school上查找它。遵循其格式,但我仍然弄错了。有人可以解释我在做什么错吗?以及如何解决它。

谢谢。

错误:

Static analysis:

3 errors were found during analysis.

A comma or a closing bracket was expected. (near "FOREIGN KEY" at position 236)
Unexpected beginning of statement. (near "user_id" at position 249)
Unrecognized statement type. (near "REFERENCES" at position 258)
SQL query:

CREATE TABLE prod_owners ( owner_id int(20) NOT NULL AUTO_INCREMENT PRIMARY KEY, user_id int(11) NOT NULL FOREIGN KEY (user_id) REFERENCES users (user_id), prod_id int(20) NOT NULL FOREIGN KEY (prod_id) REFERENCES products (prod_id) )

MySQL said: Documentation

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'FOREIGN KEY (user_id) REFERENCES users (user_id),
    prod_id         int(20)
' at line 8

代码:

CREATE TABLE users (
    user_id        int(11)
                    NOT NULL
                    AUTO_INCREMENT
                    PRIMARY KEY,
    phone           int(11)
                    NOT NULL
);

CREATE TABLE products (
    prod_id         int(20)
                    NOT NULL
                    AUTO_INCREMENT
                    PRIMARY KEY,
    info            varchar(1000)
                    NOT NULL
);

CREATE TABLE prod_owners (
    owner_id        int(20)
                    NOT NULL
                    AUTO_INCREMENT
                    PRIMARY KEY,
    user_id         int(11)
                    NOT NULL
                    FOREIGN KEY (user_id) REFERENCES users (user_id),
    prod_id         int(20)
                    NOT NULL
                    FOREIGN KEY (prod_id) REFERENCES products (prod_id)
);

1 个答案:

答案 0 :(得分:3)

您需要在列定义后添加逗号。

看下面的代码:

CREATE TABLE users(
  user_id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
  phone INT(11) NOT NULL
);
CREATE TABLE products(
  prod_id INT(20) NOT NULL AUTO_INCREMENT PRIMARY KEY,
  info VARCHAR(1000) NOT NULL
);
CREATE TABLE prod_owners(
  owner_id INT(20) NOT NULL AUTO_INCREMENT PRIMARY KEY,
  user_id INT(11) NOT NULL, FOREIGN KEY(user_id) REFERENCES users(user_id),
  prod_id INT(20) NOT NULL, FOREIGN KEY(prod_id) REFERENCES products(prod_id)
);