2012-06-15 90 views
14

当我尝试在mysql中创建表时出现错误。错误1005(HY000):无法创建表(errno:150)

解决它的任何提示?

create table stock_in(
    ind int not null auto_increment, 
    itemcode varchar(10) not null, 
    quantity int not null, 
    description text not null, 
    sales_ref int not null default -1, 
    return_outwards_ref int not null default -1, 
    stock_in_receipt_ref int not null default -1, 
    date text not null, 
    time text not null, 
    username text not null, 
    foreign key (sales_ref) references sales (receiptno), 
    foreign key (return_outwards_ref) references returnoutwards(ind), 
    primary key (ind) 
); 

的错误:

ERROR 1005 (HY000): Can't create table 'posinventory.stock_in' (errno: 150) 
+0

您是否使用唯一键创建了'sales'和'returnoutwards'表?所有表格必须是InnoDb。 – Devart

+0

@Devart:谢谢,我发现我的错误......这是因为salesno中的receiptno不是主键......我应该将它引用到具有主键的新列,例如sales_no – Boon

回答

25

退房MySQL手册约foreign key constrains

If you re-create a table that was dropped, it must have a definition that conforms to the foreign key constraints referencing it. It must have the right column names and types, and it must have indexes on the referenced keys, as stated earlier. If these are not satisfied, MySQL returns error number 1005 and refers to error 150 in the error message.

几个想法:

  • 更好的掉落并使用格式良好的语法创建新表。
  • 确保将ENGINE=InnoDB;添加到您的CREATE TABLE - 命令中。
  • 确保您的MySQL服务器上启用了InnoDB。要验证这一点,请尝试以下命令:SHOW VARIABLES LIKE 'have_innodb'; - 如果它返回YES,那么InnoDB已启用。
  • 检查您的命令是否包含表格和字段名称中的大写字母和小写字母。
  • 检查这不仅是一个你想创建的表,而且还在外键所指的表上。
  • 确保您的引用表正确编入索引。
+0

谢谢,我发现我的错误...这是因为销售表中的receiptno不是主键......我应该将它引用到具有主键的新列,例如,sales_no – Boon

+0

我也有同样的错误,并且在索引主键上的父表时,错误得到解决。 – sreeprasad

+2

我想补充一点,如果您使用FK提及的任何表格不是同一个引擎,那么您会收到该消息;好吧,如果他们不是InnoDB的话。 –

1

原因之一是外键列数据类型和长度应该与引用表键列相同。例如,引用表列是mediumint(11),而外键列是int(11)意味着在创建具有外键的表时会发生错误。

4

有完全相同的问题。它的来源是用于外键和引用的类型。

外键:

fer_id SMALLINT NOT NULL 

和原始场(refernce这是我们提供):

id INT(11) UNSIGNED NOT NULL 

我刚刚做fer_id INT(11)UNSIGNED为好。神奇的作品!

1

除此之外,您需要确保两个表/字段都与CHARSET设置相匹配。 UTF类型字段的大小可能与“latin1”的大小大不相同。 SHOW创建两个表表会告诉你,如果有一个不匹配

1

如果还原数据库备份您可以暂时禁用外键检查在.sql文件的开头插入这些字符串:

/*!40030 SET NAMES UTF8 */; 
/*!40101 SET @[email protected]@CHARACTER_SET_CLIENT */; 
/*!40101 SET @[email protected]@CHARACTER_SET_RESULTS */; 
/*!40101 SET @[email protected]@COLLATION_CONNECTION */; 
/*!40103 SET @[email protected]@TIME_ZONE */; 
/*!40103 SET TIME_ZONE='+00:00' */; 
/*!40014 SET @[email protected]@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; 
/*!40014 SET @[email protected]@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; 
/*!40101 SET @[email protected]@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; 
/*!40111 SET @[email protected]@SQL_NOTES, SQL_NOTES=0 */; 
相关问题