创建外键的语法错误

Syntax error creating a foreign key

我正在尝试创建以下 tables 设计,但我在下面收到此错误 我如何为 stops table 中的 [=12] 设置外键=] table?

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 'FOREIGN KEY REFERENCES stops(stop_id) )' at line 4

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) )" );

改变

stop_id INT FOREIGN KEY REFERENCES stops(stop_id)

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

我已经更新了查询,请注意FOREIGN KEY 的语法,那里有错误。干杯!

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) )" );

如果您查看 MySQL CREATE TABLE syntax,那么您可以选择:

内联定义(注意缺少 FOREIGN KEY

stop_id INT REFERENCES stops(stop_id)

和一个明确的定义:

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

或更好(具有命名约束):

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