2012-06-15 123 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 */; 
相關問題