简体   繁体   English

创建外键的语法错误

[英]Syntax error creating a foreign key

I am trying to create the following tables design but I am getting this error below how can I set the foreign key for the stops table in the arrivaltimes table? 我想创建下表设计,但我得到下面我怎么可以设置为外键此错误stops在表arrivaltimes表?

1064 - You have an error in your SQL syntax; 1064-您的SQL语法有误; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FOREIGN KEY REFERENCES stops(stop_id) )' at line 4 检查与您的MySQL服务器版本相对应的手册以获取正确的语法,以在第4行的“ FOREIGN KEY REFERENCES stop(stop_id))”附近使用

stt.execute("CREATE TABLE IF NOT EXISTS stops"
        + "(stop_id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, "
        + " name varchar(30) NOT NULL, " + " route INT(11) NOT NULL, "
        + " lat double(10,6) NOT NULL, "
        + " longi double(10,6)NOT NULL) ");

stt.execute("CREATE TABLE IF NOT EXISTS arrivaltimes(id INT(11) NOT NULL PRIMARY KEY,"
        + " weekday VARCHAR(20) NOT NULL,"
        + "arrivaltime time NOT NULL,"
        + " stop_id INT FOREIGN KEY REFERENCES stops(stop_id) )" );

Change 更改

stop_id INT FOREIGN KEY REFERENCES stops(stop_id)

to

stop_id INT, FOREIGN KEY fk_stop_id(stop_id) REFERENCES stops(stop_id)

I have updated the query, please take note of the syntax of the FOREIGN KEY, where you had an error. 我已经更新了查询,请记下FOREIGN KEY的语法,如果出现错误。 Cheers! 干杯!

stt.execute("CREATE TABLE IF NOT EXISTS stops"
        + "(stop_id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, "
        + " name varchar(30) NOT NULL, " + " route INT(11) NOT NULL, "
        + " lat double(10,6) NOT NULL, "
        + " longi double(10,6)NOT NULL) ");



stt.execute("CREATE TABLE IF NOT EXISTS arrivaltimes(id INT(11) NOT NULL PRIMARY KEY,"
                            + " weekday VARCHAR(20) NOT NULL,"
                            + "arrivaltime time NOT NULL,"
                            + " FOREIGN KEY (stop_id) REFERENCES stops(stop_id) )" );

If you look at the MySQL CREATE TABLE syntax , then you have the choice between: 如果您查看MySQL CREATE TABLE语法 ,则可以选择以下选项:

An inline definition (note the absence of FOREIGN KEY ) 内联定义(请注意,没有FOREIGN KEY

stop_id INT REFERENCES stops(stop_id)

and an explicit definition: 和一个明确的定义:

stop_id INT,
FOREIGN KEY (stop_id) REFERENCES stops(stop_id)

or better (with named constraint): 或更好(具有命名约束):

stop_id INT,
CONSTRAINT fk_arrivaltimes_stops FOREIGN KEY (stop_id) REFERENCES stops(stop_id)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM