Question

I've got Shade color that looks like this

CREATE TABLE `Shade` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `shade_name` varchar(250) DEFAULT NULL,
  `color_id` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=156 DEFAULT CHARSET=latin1;

And I've got Color table that needs to have a one-to-many relationship with the Shade table. So this is what I did:

CREATE TABLE `Color` (
  `id` int(11) unsigned NOT NULL,
  `color_name` varchar(250) DEFAULT NULL,
  PRIMARY KEY (`id`) 
  ,foreign key (`id`) references shade (`color_id`)
     on delete cascade
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

But I'm getting an error: Can't create table: errno: 150

Was it helpful?

Solution

You are defining your foreign key in the wrong place.

Color is your "main" table, so it shouldn't define any foreign key:

CREATE TABLE `Color` (
  `id` int(11) unsigned NOT NULL,
  `color_name` varchar(250) DEFAULT NULL,
  PRIMARY KEY (`id`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Shade is the "detail" table - it references Color (as evident by the color_id column it contains), and thus it should hold the foreign key's definition:

CREATE TABLE `Shade` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `shade_name` varchar(250) DEFAULT NULL,
  `color_id` int(11) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  FOREIGN KEY (`color_id`) references Color (`id`)
     ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=156 DEFAULT CHARSET=latin1;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top