Search code examples
mysqlsqldatabaseforeign-keysinnodb

How to create database with foreign keys


I've got an issue when I try to fill my fixtures. I've got 2 tables (client and partner).

CREATE TABLE `partner` (
  `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL,
  `client_id` int(10) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `name` (`name`),
  UNIQUE KEY `client_id` (`client_id`),
  CONSTRAINT `partner_ibfk_3` FOREIGN KEY (`client_id`) REFERENCES `client` 
  (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

CREATE TABLE `client` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `partner_id` tinyint(3) unsigned DEFAULT NULL,
  `partner_ref` varchar(7) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `partner_ref` (`partner_ref`,`partner_id`),
  KEY `partner_id` (`partner_id`),
  CONSTRAINT `client_ibfk_1` FOREIGN KEY (`partner_id`) REFERENCES `partner` 
  (`id`),
) ENGINE=InnoDB AUTO_INCREMENT=667305 DEFAULT CHARSET=utf8 PACK_KEYS=0;

When I run my fixtures I've got this issue :

ERROR 1215 (HY000) at line 863: Cannot add foreign key constraint

I supposed it's because when the table 'partner' is created, the table 'client' is not so the foreign key is not found.

However if I change and I put 'client' before 'partner', the problem it's same.

Thanks for your help !


Solution

  • I found a solution :

    I removed the constraint in the creation of 'partner' and I added this constraint after the creation of 'client' with an ALTER TABLE :

    CREATE TABLE `partner` (
      `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
      `name` varchar(20) NOT NULL,
      `client_id` int(10) unsigned NOT NULL,
      PRIMARY KEY (`id`),
      UNIQUE KEY `name` (`name`),
      UNIQUE KEY `client_id` (`client_id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
    
    CREATE TABLE `client` (
      `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
      `partner_id` tinyint(3) unsigned DEFAULT NULL,
      `partner_ref` varchar(7) DEFAULT NULL,
      PRIMARY KEY (`id`),
      UNIQUE KEY `partner_ref` (`partner_ref`,`partner_id`),
      KEY `partner_id` (`partner_id`),
      CONSTRAINT `client_ibfk_1` FOREIGN KEY (`partner_id`) REFERENCES `partner` 
      (`id`),
    ) ENGINE=InnoDB AUTO_INCREMENT=667305 DEFAULT CHARSET=utf8 PACK_KEYS=0;
    
    ALTER TABLE `partner`
    ADD CONSTRAINT `partner_ibfk_3` FOREIGN KEY (`client_id`) REFERENCES 
    `client` (`id`);