You could achieve it with function index(supported by MySQL 8.0.13 and newer):
(您可以使用函数索引(MySQL 8.0.13和更高版本支持)来实现它:)
CREATE UNIQUE INDEX myIndex ON test(gid,(CASE WHEN `type` = '1' THEN `type` END));
db<>fiddle demo
(db <> fiddle演示)
CREATE TABLE IF NOT EXISTS `test` (
`gid` INT NOT NULL,
`x` INT NOT NULL,
`y` INT NOT NULL,
`z` INT NOT NULL,
`type` INT NOT NULL,
PRIMARY KEY ( `gid`, `x`, `y`, `z` )
);
CREATE UNIQUE INDEX myIndex ON test(gid,(CASE WHEN `type` = '1' THEN `type` END));
INSERT INTO `test`(gid, x,y,z,`type`) VALUES (1,1,1,1,1);
INSERT INTO `test`(gid, x,y,z,`type`) VALUES (1,2,2,2,1);
-- Duplicate entry '1-1' for key 'myIndex'
INSERT INTO `test`(gid, x,y,z,`type`) VALUES (3,1,1,1,2);
INSERT INTO `test`(gid, x,y,z,`type`) VALUES (3,1,2,2,2);
SELECT * FROM `test`;
Can I add the unique index on table creation?
(我可以在创建表时添加唯一索引吗?)
CREATE TABLE IF NOT EXISTS `test` (
`gid` INT NOT NULL,
`x` INT NOT NULL,
`y` INT NOT NULL,
`z` INT NOT NULL,
`type` INT NOT NULL,
PRIMARY KEY ( `gid`, `x`, `y`, `z` ),
UNIQUE INDEX myIndex(gid,(CASE WHEN `type` = '1' THEN `type` END))
);
db<>fiddle demo2
(db <> fiddle demo2)