MySQL - 无法定义外键

MySQL - can't define foreign key

我正在尝试使用 Python 在 Wamp 服务器上创建 tables。有两个 tables - 人和消息。 table 消息有一列 person_id,它应该是 table 人的外键。

创建table后,通过PhpMyAdmin查看消息table中没有外键。 SQL 查询有问题吗?

创建人物:

@staticmethod
def createTablePerson():
    return "CREATE TABLE IF NOT EXISTS person (" \
           "id INT NOT NULL AUTO_INCREMENT PRIMARY KEY," \
           "name VARCHAR(100)," \
           "surname VARCHAR(100)" \
           ");"

创建消息:

@staticmethod
def createTableMessage():
    return "CREATE TABLE IF NOT EXISTS message (" \
           "id INT NOT NULL AUTO_INCREMENT PRIMARY KEY," \
           "personID INT NOT NULL REFERENCES person (id)," \
           "text VARCHAR(1000)" \
           ");"

您需要 index 该列才能添加为外键。命令应为

CREATE TABLE IF NOT EXISTS person (
           id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
           name VARCHAR(100),
           surname VARCHAR(100)
  );

CREATE TABLE IF NOT EXISTS message (
           id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
           text VARCHAR(1000),
           personID INT NOT NULL,
           INDEX personid_idx (personID),
           FOREIGN KEY (personID)  REFERENCES person (id)

           );

MySQL parses but ignores “inline REFERENCES specifications” (as defined in the SQL standard) where the references are defined as part of the column specification. MySQL accepts REFERENCES clauses only when specified as part of a separate FOREIGN KEY specification.

参考:http://dev.mysql.com/doc/refman/5.5/en/create-table.html


因此,要添加外键约束(对于支持它们的存储引擎),外键必须与列分开定义。

这样,REFERENCES 子句将被忽略:

personID INT NOT NULL REFERENCES person (id),

要 MySQL 添加外键约束,请按如下方式进行:

personID INT NOT NULL, 
...
FOREIGN KEY (personID) REFERENCES person (id),
...