2015-06-27 46 views
1

我正在嘗試創建一個帶有外鍵的表。我想模擬一個可以成爲另一個類別的孩子的類別。這是我的SQL:MySQL一直在抱怨外鍵。錯誤150

CREATE TABLE IF NOT EXISTS `recipes`.`category` (
    `id` INT NOT NULL COMMENT '', 
    `name` VARCHAR(60) NOT NULL COMMENT '', 
    `description` VARCHAR(255) NULL COMMENT 'Description of the recipe category.', 
    `parent_id` INT NULL COMMENT '', 
    PRIMARY KEY (`id`) COMMENT '', 
    CONSTRAINT `parent_id` 
    FOREIGN KEY (`id`) 
    REFERENCES `recipes`.`category` (`id`) 
    ON DELETE NO ACTION 
    ON UPDATE NO ACTION); 

然而,MySQL總是給我一個錯誤:

Can't create table 'recipes.category' (errno: 150)

我試圖找出我在做什麼錯了,任何人都可以給我一個提示? Docs說:

Cannot create table. If the error message refers to error 150, table creation failed because a foreign key constraint was not correctly formed.

但是,這並沒有多大幫助。

回答

2

我猜你想與外鍵parent_id列鏈接到id柱(而不是idid)建立一個層次結構。否則,它並沒有多大意義:

constraint `parent_id` 
foreign key (`parent_id`) 
references `category` (`id`) 
on delete no action 
on update no action); 

SQLFiddle