Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql cross-database foreign key

I am trying to create a cross database foreign key. When I run the following code on the same database

CREATE TABLE `t1` (
  `id` int(11) NOT NULL AUTO_INCREMENT,  
  `int_id` varchar(128) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `int_id` (`int_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

CREATE TABLE `t2` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `ext_id` varchar(128) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`),
  KEY `ext_id` (`ext_id`),
  CONSTRAINT `t2_ibfk_1` FOREIGN KEY (`ext_id`) REFERENCES `t1` (`int_id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

However, when create t1 on one databse (d1) and then run the following code on a second databse (d2), I receive the generic error: #1005 - Can't create table 'userdata.t2' (errno: 150)

CREATE TABLE `t2` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `ext_id` varchar(128) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`),
  KEY `ext_id` (`ext_id`),
  CONSTRAINT `t2_ibfk_1` FOREIGN KEY (`ext_id`) REFERENCES `d1.t1` (`int_id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Any help will be appreciated. Thanks!

like image 768
sagibb Avatar asked Mar 21 '13 00:03

sagibb


People also ask

Can you have foreign keys across databases?

And cross-schema foreign keys are perfectly fine, but you can't do cross-database fkeys.

How do I add a foreign key to a different database?

You would need to manage the referential constraint across databases using a Trigger. Basically you create an insert, update trigger to verify the existence of the Key in the Primary key table. If the key does not exist then revert the insert or update and then handle the exception.

Can you link 2 foreign keys?

In a word, yes. You can have as many foreign keys as you want referencing the same primary key.

Can two tables share a foreign key?

When you're using a foreign key to reference a column in another table, the datatypes of both tables have to be the same. For example, if the referencing column where you're declaring the foreign key uses the INT data type, then the referenced column must be INT as well.


1 Answers

Your syntax is not correct, try this

CREATE TABLE `t2` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `ext_id` varchar(128) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`),
  KEY `ext_id` (`ext_id`),
  CONSTRAINT `t2_ibfk_1` FOREIGN KEY (`ext_id`) REFERENCES `d1`.`t1` (`int_id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
like image 70
shibormot Avatar answered Oct 17 '22 23:10

shibormot