请考虑以下 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)
);
如果我做 a 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 只是它们自己。不向 person 添加任何行:
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)
为什么我的外键不起作用?