Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: foreign key constraint not enforced

I have two tables as follows:

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
);

Then I ran the following:

INSERT INTO customer (name) VALUES ('Customer1');

Now the table customer contains name: Customer1, id: 1

Then I ran this:

INSERT INTO client (name, customer_id) VALUES ('Client of Customer1',34);

It was supposed to fail, but it inserted successfully. Why is that?

This is on MySQL 5.1 on Linux Mint.

like image 377
R.V. Avatar asked Oct 09 '22 10:10

R.V.


1 Answers

Do a show create table customer. It'll show the engine used at the end of the dumped create table statement. If they're showing as MyISAM, that engine doesn't suport foreign keys. The FK definitions are parsed, but otherwise ignored.

To force a table to be Inno DB, which DOES support foren keys, you have to do

CREATE TABLE ( ... blah blah blah ...) TYPE=InnoDB;
                                       ^^^^^^^^^^^--force InnoDB type
like image 184
Marc B Avatar answered Oct 11 '22 01:10

Marc B