2013-11-04 50 views
0

這裏是我的代碼MySQL的語法錯誤 - 無法創建表

CREATE TABLE IF NOT EXISTS items 
( 
id INT NOT NULL AUTO_INCREMENT, 
name varchar(256) , 
description TEXT, 
price INT , 
images TEXT, 
views INT , 
hidden TEXT, 
purchases INT, 
PRIMARY KEY (id) 
); 

CREATE TABLE IF NOT EXISTS methods 
( 
method_id INT NOT NULL AUTO_INCREMENT, 
method varchar(256), 
username varchar(256), 
password varchar(256), 
PRIMARY KEY (method_id) 
); 

CREATE TABLE IF NOT EXISTS payments 
( 
payment_id INT NOT NULL AUTO_INCREMENT, 
item_id INT NOT NULL, 
method varchar(256), 
display INT, 
PRIMARY KEY (payment_id) , 
FOREIGN KEY (item_id) REFERENCES items (id) ON DELETE CASCADE ON UPDATE CASCADE, 
FOREIGN KEY (method) REFERENCES methods (method) ON DELETE CASCADE ON UPDATE CASCADE 
)ENGINE=InnoDB DEFAULT CHARSET=latin1; 

第2個表獲取生成不錯,但第三個「支付」給我的錯誤代碼150!這應該與FK有關?

有幫助嗎?

回答

1

方法表中的主鍵是method_id而不是method。和數據類型是INTVARCHAR(256)

您需要:

CREATE TABLE IF NOT EXISTS payments 
( 
    payment_id INT NOT NULL AUTO_INCREMENT, 
    item_id INT NOT NULL, 
    method_id int, -- this is different 
    display INT, 
    PRIMARY KEY (payment_id) , 
    FOREIGN KEY (item_id) REFERENCES items (id) ON DELETE CASCADE ON UPDATE CASCADE, 

    -- and this line is different 
    FOREIGN KEY (method_id) REFERENCES methods (method_id) ON DELETE CASCADE ON UPDATE CASCADE 
) ENGINE=InnoDB DEFAULT CHARSET=latin1; 
+0

謝謝,但爲什麼我不能只是指任何列?爲什麼不能將FK設置爲​​'method'而不是'method_id'? – Newbie

+0

@Newbie:外鍵只能引用主鍵(或唯一約束)。想一想:如果在「目標」列中有多個具有相同值的行,哪一個應該是引用行的目標? –

+0

我明白了,我仍然是新的php/mysql ..設置「方法」是一個獨特的列也解決了我的問題,謝謝 – Newbie