Question

why the foreign key gives my headache?
first i created database names colorcode then paper table which works fine:

CREATE TABLE paper (
  paper_id int(20) NOT NULL,
  description VARCHAR(40) NOT NULL,
  paper_color VARCHAR(40) NOT NULL,
  PRIMARY KEY (paper_id, paper_color)
) ENGINE=InnoDB;

then brick table

CREATE TABLE brick(
  brick_id int(20) NOT NULL,
  description varchar(40) NOT NULL,
  brick_color varchar (40) NOT NULL,
  PRIMARY KEY (brick_id),
  FOREIGN KEY (brick_color) REFERENCES paper(paper_color)
) ENGINE=InnoDB;

which doesn't=>

#1005 - Can't create table 'colorcode.brick' (errno: 150)

thank you for your help

Was it helpful?

Solution 2

Create a separate key for paper_color and it will work:

CREATE TABLE paper (
    paper_id int(20) not null,
    description VARCHAR(40)not null,
    paper_color VARCHAR(40) NOT NULL,
    PRIMARY KEY (paper_id, paper_color),
    KEY (paper_color)
) ENGINE=InnoDB;

OTHER TIPS

create table paper (
  paper_id int(20) not null,
  description VARCHAR(40)not null,
  paper_color VARCHAR(40) NOT NULL,
  primary key (paper_id, paper_color),
  INDEX(`paper_color`)
)engine=InnoDB;

create table brick (
  brick_id int(20) not null,
  description varchar(40) not null,
  brick_color varchar (40) not null,
  primary key (brick_id), 

  CONSTRAINT foreign key (`brick_color`) REFERENCES  paper(`paper_color`)
)engine=InnoDB;

Demo: http://sqlfiddle.com/#!2/316d9

InnoDB permits a foreign key to reference any index column or group of columns. However, in the referenced table, there must be an index where the referenced columns are listed as the first columns in the same order.

http://dev.mysql.com/doc/refman/5.6/en/innodb-foreign-key-constraints.html

"paper_color" has to be an index in order to reference.

Hope this helps.

From SQL FOREIGN KEY Constraint

A FOREIGN KEY in one table points to a PRIMARY KEY in another table.

Now from your script, the PRIMARY KEY on table paper consists of columns paper_id, paper_color, but the foreign key referenceing it, only references paper(paper_color)

This techinically allows you to have 2 entries with

paper_id    paper_color
1           blue
2           blue

which would satisfy the primary key constraint of table paper, but not the foreign key constraint on table brick

Changing the primary key on table paper to only paper_color would work though.

create table paper (
paper_id int(20) not null,
description VARCHAR(40)not null,
paper_color VARCHAR(40) NOT NULL,
primary key ( paper_color)
)engine=InnoDB;

create table brick(
brick_id int(20) not null,
description varchar(40) not null,
brick_color varchar (40) not null,
primary key (brick_id),
foreign key (brick_color) references paper(paper_color)
)engine=InnoDB

SQL Fiddle DEMO

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top