简体   繁体   中英

Error on creating foreign key relationship between non-primary key

I have two table

CREATE TABLE `abc` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`ref_id` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `ref_id_UNIQUE` (`ref_id`)
)

CREATE TABLE `xyz` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `ref_id` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `ref_id_UNIQUE` (`ref_id`)
 )

I want to make foreign key relation ship between xyz's ref_id and abc's ref_id .But Mysql gives error 1215.

You should make the foreign key relationships to the primary keys . I know that MySQL allows foreign key relationships to anything with an index. But the correct practice is to use primary keys.

So declare the table like this:

CREATE TABLE `xyz` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
  abc_id int DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `ref_id_UNIQUE` (`abc_id`),
  ADD CONSTRAINT fk_xyz_abc FOREIGN KEY (abc_id) REFERENCES abc(id)
);

If you want the ref_id for an xyz row, then use JOIN to get the information.

Take a look at Gordon Linoff's answer, his suggestion makes sense, even though it does not answer the question. So what can cause an error when you intend to create a foreign key relationship? The obvious possibility is syntax error and typo, so you will need to check against those and fix any such problems.

Another possibility is that you have inconsistency, that is, you try to create a foreign key constraint in one of your table s, but not all the values have exact matches. So, assuming that you have Foo and Bar table and you intend Foo.lorem to be a foreign key referencing Bar.ipsum , then you will need to ensure that all the values you have for Foo.lorem has a Bar.ipsum pair with the exact same values (except null ). If that's not true, then your foreign key constraint will not be successfully created. Find such inconsistencies:

select distinct Foo.lorem
from Foo
where not (Foo.lorem is null) and
not exists (select 1 from Bar where Foo.lorem = Bar.ipsum);

Read the lines carefully and make sure you fix any such Foo.lorem values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM