Home > MySQL > MySQL Error: #1005 – Can't create table '….#sql-e7c_89.frm' (errno: 150)

MySQL Error: #1005 – Can't create table '….#sql-e7c_89.frm' (errno: 150)

Se estiverem a tentar criar uma relação entre duas tabelas usando o MySQL e obtiverem o seguinte erro:

#1005 - Can't create table '.\twitta\#sql-e7c_89.frm' (errno: 150)

Experimentem activar o modo de debug do motor de innoDB de forma a obter mais informações sobre o erro e a poderem-no perceber.

Para tal digitem na vossa consola:

mysql> SHOW ENGINE INNODB STATUS;

E agora fazendo scroll para para cima sobre o output apresentado podem ver uma mensagem de erro mais detalhada. no meu caso foi:

------------------------
LATEST FOREIGN KEY ERROR
------------------------
090801 23:41:40 Error in foreign key constraint of table twitta/#sql-e7c_8a:
 FOREIGN KEY ( `user_id` ) REFERENCES `users` ( `id` ) ON DELETE CASCADE:
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
See http://dev.mysql.com/doc/refman/5.0/en/innodb-foreign-key-constraints.html
for correct foreign key definition.

Depois de consultar a documentação que o modo de debug sugere, rapidamente me apercebi do meu erro. A tabela onde estava criar a chave estrangeira o campo referenciado não estava indexado. Como se pode ler na documentação:

InnoDB requires indexes on foreign keys and referenced keys so that foreign key
checks can be fast and not require a table scan. In the referencing table,
there must be an index where the foreign key columns are listed as the first
columns in the same order. Such an index is created on the referencing table
automatically if it does not exist. (This is in contrast to some older versions,
in which indexes had to be created explicitly or the creation of foreign key
constraints would fail.) index_name, if given, is used as described previously

Espero que isto vós ajude.

Categories: MySQL Tags: , ,
  1. Rubens
    August 7th, 2009 at 02:59 | #1

    obrigado por compartilhar a informação, enfrentei o mesmo erro e com sua dica localizei rapidamente!

  1. No trackbacks yet.