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.
譯文:在「被參考的表」中找不到包含「被參考欄位」的索引,或兩個關聯欄位型別不匹配。
執行 SHOW ENGINE INNODB STATUS 可查看 LATEST FOREIGN KEY ERROR 詳細資訊。
CREATE TABLE booktype (
btid INT(5) UNSIGNED ZEROFILL AUTO_INCREMENT NOT NULL PRIMARY KEY,
btname VARCHAR(100) NOT NULL UNIQUE,
btnote TEXT
);
CREATE TABLE books (
bid INT(5) UNSIGNED ZEROFILL AUTO_INCREMENT NOT NULL PRIMARY KEY,
bname CHAR(30) NOT NULL,
isbn CHAR(50) NOT NULL,
author CHAR(30) NOT NULL,
press TEXT,
summary TEXT,
bcount INT NOT NULL DEFAULT 0,
btid INT, -- 此處型別缺少 UNSIGNED ZEROFILL
FOREIGN KEY (btid) REFERENCES booktype(btid)
);
錯誤: ERROR 1005 (HY000): Can't create table '.\bookdata\books.frm' (errno: 150)
解決: 將 books.btid 定義為 INT(5) UNSIGNED ZEROFILL,與 booktype.btid 完全一致。
CREATE TABLE products (
id INT NOT NULL AUTO_INCREMENT,
title VARCHAR(100) NOT NULL,
description TEXT NOT NULL,
image_url VARCHAR(200) NOT NULL,
price DECIMAL(10,2) NOT NULL,
date_available DATETIME NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB;
CREATE TABLE line_items (
id INT NOT NULL AUTO_INCREMENT,
product_id INT NOT NULL,
quantity INT NOT NULL DEFAULT 0,
unit_price DECIMAL(10,2) NOT NULL,
CONSTRAINT fk_items_product FOREIGN KEY (product_id) REFERENCES products(id), -- 此處拼寫錯誤 producets
INDEX (product_id),
PRIMARY KEY (id)
) ENGINE=InnoDB;
問題:
producets 應為 productsproducts.id 已為主鍵(含索引),但 line_items.product_id 需顯式建立 INDEX(已做)關鍵原則: