I just want to create a new table on my database, but doing so:
CREATE TABLE `houses` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`room_id` int(11) NOT NULL,
`car_id` int(11) NOT NULL UNIQUE,
`name` varchar(128) NOT NULL,
`is_deleted` tinyint(1) DEFAULT 0,
`sell_at` datetime NULL DEFAULT NULL,
`created_at` datetime NOT NULL DEFAULT current_timestamp(),
`updated_at` datetime NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
PRIMARY KEY (`id`),
KEY `room_id` (`room_id`),
KEY `car_id` (`car_id`),
CONSTRAINT `houses_ibfk_1`
FOREIGN KEY (`room_id`)
REFERENCES `rooms` (`id`),
CONSTRAINT `houses_ibfk_2`
FOREIGN KEY (`car_id`)
REFERENCES `cars` (`id`)
ON DELETE CASCADE
ON UPDATE NO ACTION
);
Return me the error:
ERROR 1061 (42000): Duplicate key name 'car_id'
I don't have any car_id
elsewhere, even in this:
SELECT (
table_schema, table_name, constraint_name
) FROM information_schema.table_constraints
WHERE table_schema
ORDER by table_schema, table_name;
What am I doing wrong ? is it because of the car_id's UNIQUE
property ? it works without, but I want to be sure each houses's car is unique (no other house will use them).
And each houses
's owner will have a cars
when buying (creating) their house.
The error is because the definition has:
KEY `car_id` (`car_id`),
Which, by itself, is not a problem, but with the UNIQUE
keyword applied to the column, the table will be created with:
UNIQUE KEY `car_id` (`car_id`)
... so the car_id
becomes a duplicated KEY
reference when both are present.
Simply remove the:
KEY `car_id` (`car_id`),
from the create definition, and it will work as expected.
See this dbfiddle with the part to remove commented-out. That includes an example error reusing a car's id, plus the output of the created table definition too.