Mysql创建外键

时间:2013-05-24 18:02:07

标签: python mysql sql foreign-keys

我需要为Reviewers_POS表创建一个外键。 我将Reviewers_Id作为我的主键,我想将它从Reviewrs_POS表传递给我的id_r1 ..

    import MySQLdb as mdb
    import sys


    conexao = mdb.connect('localhost', 'root', 'rot', 'DbOmelete')
    with conexao:  
    cur = conexao.cursor()

   cur.execute("CREATE TABLE IF NOT EXISTS Reviewers(Reviewers_Id int unsigned not null AUTO_INCREMENT, PRIMARY KEY (Reviewers_Id),Title varchar(500), Polarity INT, Review TEXT);")
   cur.execute("CREATE TABLE IF NOT EXISTS Reviewers_POS(ReviewersPOS_Id int unsigned not null PRIMARY KEY AUTO_INCREMENT, Review_POS TEXT,id_r1 integer,CONSTRAINT fk_id FOREIGN KEY (id_r1) REFERENCES Reviewers (Reviewers_Id));")

__ 我收到了这个错误:

追踪(最近一次呼叫最后一次):

  File "SQLTesteForeign.py", line 14, in <module>
    cur.execute("CREATE TABLE IF NOT EXISTS Reviewers_POS(ReviewersPOS_Id int unsigned not null PRIMARY KEY AUTO_INCREMENT, Review_POS TEXT,id_r1 integer,CONSTRAINT fk_id FOREIGN KEY (id_r1) REFERENCES Reviewers (Reviewers_Id) ON DELETE NO ACTION ON UPDATE NO ACTION);")
  File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 174, in execute
    self.errorhandler(self, exc, value)
  File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
    raise errorclass, errorvalue
_mysql_exceptions.OperationalError: (1005, "Can't create table 'DbOmelete.Reviewers_POS' (errno: 150)")

有人知道如何解决它吗?我想我错过了什么......因为我真的不知道“哪里”是错误..

1 个答案:

答案 0 :(得分:2)

您的主键是int unsigned类型,而您的外键类型为integer,两者不兼容。将您的外键更改为int unsigned,表格将成功创建。

An SQLfiddle to test with