我正在尝试创建数据库,我编写了代码,当我将其导入phpMyAdmin时,我收到以下错误:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'OPTION(OPTION_ID)
)' at line 7
和我写的代码:
CREATE DATABASE MAWARID;
USE MAWARID;
CREATE TABLE TOPIC (
TOPIC_ID INT NOT NULL AUTO_INCREMENT,
TOPIC_NAME VARCHAR(30) NOT NULL,
PRIMARY KEY (TOPIC_ID)
);
CREATE TABLE QUESTION (
QUESTION_ID INT NOT NULL AUTO_INCREMENT,
QUESTION_NAME VARCHAR(100) NOT NULL,
ANSWER INT NOT NULL,
PRIMARY KEY (QUESTION_ID),
FOREIGN KEY (ANSWER) REFERENCES OPTION(OPTION_ID)
);
CREATE TABLE OPTION (
OPTION_ID INT NOT NULL AUTO_INCREMENT,
OPTION_NAME VARCHAR(100) NOT NULL,
QUESTION INT NOT NULL,
PRIMARY KEY (OPTION_ID),
FOREIGN KEY (QUESTION) REFERENCES QUESTION(QUESTION_ID)
);
我在这里检查了其他错误#1064问题,但似乎没有帮助我。
有关我为什么会收到此错误的想法?
答案 0 :(得分:2)
OPTION
是MySQL中的保留字。
你需要添加反引号``,改变你的
CREATE TABLE OPTION
到
CREATE TABLE `OPTION`
注意:反引号`键与美国键盘上的波形符~
键位于同一按钮上。
答案 1 :(得分:2)
脚本中存在循环依赖关系:QUESTION引用OPTION,反之亦然。
CREATE TABLE QUESTION (
[...]
FOREIGN KEY (ANSWER) REFERENCES OPTION(OPTION_ID)
);
CREATE TABLE OPTION (
[...]
FOREIGN KEY (QUESTION) REFERENCES QUESTION(QUESTION_ID)
);
要么删除它们(循环依赖通常是设计缺陷),要么稍后在QUESTION中尝试添加外键:
CREATE DATABASE MAWARID;
USE MAWARID;
CREATE TABLE TOPIC (
TOPIC_ID INT NOT NULL AUTO_INCREMENT,
TOPIC_NAME VARCHAR(30) NOT NULL,
PRIMARY KEY (TOPIC_ID)
);
CREATE TABLE QUESTION (
QUESTION_ID INT NOT NULL AUTO_INCREMENT,
QUESTION_NAME VARCHAR(100) NOT NULL,
ANSWER INT NOT NULL,
PRIMARY KEY (QUESTION_ID)
-- no foreign key creation here
);
CREATE TABLE `OPTION` (
OPTION_ID INT NOT NULL AUTO_INCREMENT,
OPTION_NAME VARCHAR(100) NOT NULL,
QUESTION INT NOT NULL,
PRIMARY KEY (OPTION_ID),
FOREIGN KEY (QUESTION) REFERENCES QUESTION(QUESTION_ID)
);
-- create your foreign key here
ALTER TABLE QUESTION ADD FOREIGN KEY (ANSWER) REFERENCES `OPTION`(OPTION_ID);
此外,OPTION是一个保留字,您最好将其封装在后备或选择其他名称。