简体   繁体   English

MySQL-无法定义外键

[英]MySQL - can't define foreign key

I'm trying to create tables on Wamp server using Python. 我正在尝试使用Python在Wamp服务器上创建表。 There are two tables - person and message. 有两个表-人员和消息。 The table message has a column person_id which should be a foreign key for table person. 表消息具有一列person_id,该列应为表人员的外键。

After the tables are created, there is no foreign key in message table when I look at it via PhpMyAdmin. 创建表后,通过PhpMyAdmin查看消息表中没有外键。 Is there something wrong with SQL queries? SQL查询有问题吗?

Creation of person: 创造人:

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

Creation of message: 消息创建:

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

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解析但忽略“内联REFERENCES规范”(如SQL标准所定义),其中引用被定义为列规范的一部分。 MySQL accepts REFERENCES clauses only when specified as part of a separate FOREIGN KEY specification. MySQL仅在作为单独的FOREIGN KEY规范的一部分指定时才接受REFERENCES子句。

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


So, to add a foreign key constraint (for storage engines that support them), the foreign key has to be defined separately from the column. 因此,要添加外键约束(对于支持它们的存储引擎),必须与列分开定义外键。

With this, the REFERENCES clause is ignored: 这样,REFERENCES子句将被忽略:

personID INT NOT NULL REFERENCES person (id),

To have MySQL add a foreign key constraint, do it like this: 要让MySQL添加外键约束,请按照以下步骤操作:

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

You need to index the column before adding as foreign key. 在添加为外键之前,您需要index该列。 The commands should be as 命令应为

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)

           );

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

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