2010-02-23 37 views
1

這是對這個問題的進一步討論:幾個類似的DDL不同的結果外鍵

Why is it still possible to insert a foreign key that doesn't exist?

這工作:

CREATE TABLE products (
    id integer unsigned auto_increment primary key 
) ENGINE=INNODB; 

CREATE TABLE orders (
    id integer PRIMARY KEY auto_increment, 
    product_id integer unsigned, 
    quantity integer, 
    INDEX product_id_idx (product_id), 
    FOREIGN KEY (product_id) REFERENCES products (id) 
) ENGINE=INNODB; 

但這些2不是:

A

CREATE TABLE products (
    id integer unsigned auto_increment primary key 
) ENGINE=INNODB; 

CREATE TABLE orders (
    id integer PRIMARY KEY auto_increment, 
    product_id integer unsigned REFERENCES products (id), 
    quantity integer, 
    INDEX product_id_idx (product_id) 
); 

CREATE TABLE products (
    id integer auto_increment primary key 
) ENGINE=INNODB; 

CREATE TABLE orders (
    id integer PRIMARY KEY auto_increment, 
    product_id integer unsigned, 
    quantity integer, 
    INDEX product_id_idx (product_id), 
    FOREIGN KEY (product_id) REFERENCES products (id) 
) ENGINE=INNODB; 

對於,這是因爲integer primary key相同integer unsigned primary key

你能解釋爲什麼一個不工作?

回答

0

A不起作用,因爲InnoDB不識別或支持「內聯參考規範」的語法。他們簡單地被忽略。

B不起作用,因爲引用列和引用列需要是完全相同的類型。 「整數類型的大小和符號必須相同。」 MySQL的數字數據類型默認爲signed,所以你必須明確指定unsigned屬性。您可以測試INT AUTO_INCREMENT PRIMARY KEY並不意味着unsigned

CREATE TABLE a (a INT NOT NULL AUTO_INCREMENT PRIMARY KEY) ENGINE=INNODB; 
INSERT INTO a VALUES(-5); 
SELECT * FROM a; 

來源和補充閱讀:

+0

但是,正如我在我的崗位,'主鍵說'暗示'無符號',對吧? – user198729 2010-02-23 21:19:15

+0

@ user198729:沒有暗示。 MySQL數字數據類型默認是簽名的,所以你必須明確指定'unsigned'屬性:http://dev.mysql.com/doc/refman/5.1/en/numeric-type-overview.html – 2010-02-23 21:30:13

+0

對於* * A **,如果內聯引用不被InnoDB識別,那麼它們用於什麼? – user198729 2010-02-23 21:40:38

相關問題