-3
請考慮以下SQL。我試圖創建一個引用另一個表的表。外鍵沒有被執行,我不知道爲什麼。爲什麼這個外鍵參考不起作用?
--drop database test;
create database test;
use test;
create table person (
id int auto_increment,
name varchar(30),
primary key (id)
);
create table message (
id int auto_increment,
senderid int,
receiverid int,
primary key (id),
foreign key (senderid) references person(id),
foreign key (receiverid) references person(id)
);
如果我做了SHOW CREATE TABLE message
,我得到如下:
CREATE TABLE `message` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`senderid` int(11) DEFAULT NULL,
`receiverid` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `senderid` (`senderid`),
KEY `receiverid` (`receiverid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
注意,外鍵senderid/receiverid只是自己。無需添加任何行:
mysql> insert into message (senderid, receiverid) values (1,2);
Query OK, 1 row affected (0.00 sec)
mysql> select * from person;
Empty set (0.00 sec)
mysql> select * from message;
+----+----------+------------+
| id | senderid | receiverid |
+----+----------+------------+
| 1 | 1 | 2 |
+----+----------+------------+
1 row in set (0.00 sec)
爲什麼我的外鍵不工作?
我認爲你需要使用InnoDB才能夠使用外鍵:http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html –
似乎正在工作on [SQLFiddle](http://sqlfiddle.com/#!2/948cf)(*嘗試取消註釋然後生成,它會產生錯誤。*) –
@JohnWoo:sqlfiddle的默認存儲引擎是InnoDB。上面的「SHOW CREATE TABLE」輸出顯示引擎是「MyISAM」。 – eggyal