我有两张表如下:
CREATE TABLE customer
(
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(25),
PRIMARY KEY(id)
);
CREATE TABLE `client`
(
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(200),
`customer_id` INT NOT NULL,
PRIMARY KEY(`id`),
INDEX(`customer_id`),
FOREIGN KEY (`customer_id`) REFERENCES `customer`(`id`) ON UPDATE CASCADE ON DELETE RESTRICT
);
然后我运行了以下内容:
INSERT INTO customer (name) VALUES ('Customer1');
现在,表客户包含名称:Customer1,id:1
然后我跑了这个:
INSERT INTO client (name, customer_id) VALUES ('Client of Customer1',34);
它应该失败,但它成功插入。那是为什么?
这是Linux Mint上的MySQL 5.1。
答案 0 :(得分:3)
做show create table customer
。它将显示转储create table
语句末尾使用的引擎。如果它们显示为MyISAM,则该引擎不会支持外键。解析FK定义,否则忽略。
要强制一个表是Inno DB,它支持foren键,你必须这样做
CREATE TABLE ( ... blah blah blah ...) TYPE=InnoDB;
^^^^^^^^^^^--force InnoDB type
答案 1 :(得分:1)
可能是引擎问题,只是为了确保在创建表时添加引擎:
CREATE TABLE customer
(
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(25),
PRIMARY KEY(id)
) ENGINE=INNODB;
CREATE TABLE `client`
(
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(200),
`customer_id` INT NOT NULL,
PRIMARY KEY(`id`),
INDEX(`customer_id`),
FOREIGN KEY (`customer_id`) REFERENCES `customer`(`id`) ON UPDATE CASCADE ON DELETE RESTRICT
) ENGINE=INNODB;