Q
Q
Qixing2015-02-18 06:44:53
MySQL
Qixing, 2015-02-18 06:44:53

How to add a foreign key to a table on a null column with already existing records?

Good afternoon. There is a table brands (brand) and goods (item). The products have a brand column, which I want to make a foreign key on brand.id. But the item.brand field can be null. The table already has records. Where there are no links brand=null.

ALTER TABLE  `item` ADD FOREIGN KEY (  `brand` ) REFERENCES  `imstor`.`brand` (

`id`
) ON DELETE RESTRICT ON UPDATE RESTRICT ;

Ответ MySQL: Документация

#1215 - Cannot add foreign key constraint

CREATE TABLE IF NOT EXISTS `brand` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`category` int(10) NOT NULL,
`url` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
KEY `category_id` (`category`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=22 ;

-- --------------------------------------------------------

--
-- Структура таблицы `item`
--

CREATE TABLE IF NOT EXISTS `item` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`category` int(10) NOT NULL,
`url` varchar(255) NOT NULL,
`brand` int(10) DEFAULT NULL,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
KEY `category_id` (`category`),
KEY `brand` (`brand`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=420 ;

ALTER TABLE `brand`
ADD CONSTRAINT `brand_ibfk_1` FOREIGN KEY (`category`) REFERENCES `category` (`id`);

ALTER TABLE `item`
ADD CONSTRAINT `item_ibfk_1` FOREIGN KEY (`category`) REFERENCES `category` (`id`);

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vinatorul, 2015-02-18
@Qixing

Try like this

ALTER TABLE  `item` ADD CONSTRAINT 'fk_brand_id' FOREIGN KEY (`brand`) REFERENCES  `imstor`.`brand`(`id`) 
ON DELETE RESTRICT ON UPDATE RESTRICT;

Z
zhogar, 2015-02-18
@zhogar

most likely is null and not equal, although I could be wrong.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question