开发者

MySQL unique composite constraint not working

I've created a unique index like this:

ALTER TABLE items 
ADD UNIQUE INDEX uni_item 
(warehouse_id, width, height, depth, weight);

but I still can add duplicate items, why is this not working?

Note:

The table itself also has some columns that are not included here, and warehouse_id is a foreign key, but these things shouldn't matter, right?

Thanks!

@cularis: here is the example of successfully added duplicates:

item_id, warehouse_id, width, height, depth, weight, date
1              4        100    100     100     14     2011-08-07 07:01:26


item_id, warehouse_id, width, height, depth, weight, date
6              4        100    100     100     14     2011-08-07 07:01:32

EDIT:

Adding more info as required:

CREATE TABLE `items`开发者_如何学Go (
 `item_id` int(11) NOT NULL AUTO_INCREMENT,
 `warehouse_id` int(11) NOT NULL,
 `width` decimal(3,2) NOT NULL,
 `height` decimal(3,2) NOT NULL,
 `depth` decimal(3,2) NOT NULL,
 `weight` decimal(3,2) NOT NULL,
 `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY `uni_item` (`warehouse_id`,`width`,`height`,`depth`,`weight`),
KEY `warehouse_id` (`warehouse_id`),
CONSTRAINT `items_ibfk_1` FOREIGN KEY (`warehouse_id`) REFERENCES `warehouses` (`warehouse_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci






 INSERT INTO `main`.`items` (
`item_id` ,
`warehouse_id` ,
`width` ,
`height` ,
`depth` ,
`weight` ,
`date`
)
VALUES (
NULL , '4', 100, 100, 100, 14, CURRENT_TIMESTAMP
)


Not reproducible on mysql 5.1.58

CREATE TABLE `items` (
 `item_id` int(11) NOT NULL,
 `warehouse_id` int(11) NOT NULL,
 `width`  decimal(3,2) NOT NULL,
 `height`  decimal(3,2) NOT NULL,
 `depth`  decimal(3,2) NOT NULL,
 `weight`  decimal(3,2) NOT NULL,
 `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
 PRIMARY KEY (`item_id`),
 UNIQUE KEY `uni_item` (`warehouse_id`,`width`,`height`,`depth`,`weight`), 
 KEY `warehouse_id` (`warehouse_id`), 
 CONSTRAINT `items_ibfk_1` FOREIGN KEY (`warehouse_id`) 
    REFERENCES `warehouses` (`warehouse_id`) ON DELETE CASCADE ON UPDATE CASCADE 
) ENGINE=InnoDB;

CREATE TABLE `warehouses` (
 `warehouse_id` int(11) NOT NULL,
 `data` text,
 PRIMARY KEY (`warehouse_id`)
) ENGINE=InnoDB;

insert into warehouses values (4, 'test');
Query OK, 1 row affected (0.01 sec)

results in:

mysql> insert into items values (1,4,100,100,100,14,'2011-08-07 07:01:26');
Query OK, 1 row affected (0.01 sec)
mysql> insert into items values (6,4,100,100,100,14,'2011-08-07 07:01:32');
ERROR 1062 (23000): Duplicate entry '4-9.99-9.99-9.99-9.99' for key 'uni_item'

EDIT: use table definitions provided in question


thanks very much for all the help.

Seems something was wrong with my installation, I've now reinstalled the whole server and the constraint works just fine.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜