Mysql 尝试使用外键生成表时出错
我正在制作一个简单的3表数据库。然而,当我尝试创建prod_owners表时,我总是得到一个错误。我不明白为什么。我试着在学校的网站上查。按照它的格式,我还是弄错了。有人能解释一下我做错了什么吗?以及我如何可能修复它 错误:Mysql 尝试使用外键生成表时出错,mysql,Mysql,我正在制作一个简单的3表数据库。然而,当我尝试创建prod_owners表时,我总是得到一个错误。我不明白为什么。我试着在学校的网站上查。按照它的格式,我还是弄错了。有人能解释一下我做错了什么吗?以及我如何可能修复它 错误: Static analysis: 3 errors were found during analysis. A comma or a closing bracket was expected. (near "FOREIGN KEY" at position 236) U
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)
);
尝试按说明定义用逗号分隔的外键,而不是用列声明。@Ishaan我就是这么做的?所以我认为您在用户id声明和外键声明之间缺少一个逗号。这就是我要说的@mark我不能在为外键声明列的同一行声明外键吗key@Mark是的,您可以在同一行中声明,但需要在列后添加逗号definition@RaviSachaniya你能给我举一个在同一条线上做这件事的例子吗
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)
);