我正在尝试使用 Python 在 Wamp 服务器上创建表。有两个表 - 人员和消息。表 message 有一个列 person_id ,它应该是表 person 的外键。
创建表后,当我通过 PhpMyAdmin 查看消息表时,消息表中没有外键。 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)" \
");"
最佳答案
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 acceptsREFERENCES
clauses only when specified as part of a separateFOREIGN 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),
...
关于python - MySQL - 无法定义外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28528932/