CREATE UNIQUE INDEX idx_product_id ON t_relation (product_id) WHERE deleted = 'N' > 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE deleted = 'N'' at line 1 > 时间: 0.027s
时间: 2023-07-03 07:30:42 浏览: 93
很抱歉,我的回答有误。在MySQL中,不能在创建索引时使用WHERE子句来限制唯一性。正确的做法是创建一个带有唯一性约束和删除标记的复合索引,如下所示:
```
CREATE TABLE t_relation (
id INT PRIMARY KEY AUTO_INCREMENT,
product_id INT NOT NULL,
deleted CHAR(1) NOT NULL DEFAULT 'N',
INDEX idx_product_id_deleted (product_id, deleted),
CONSTRAINT uc_product_id_deleted UNIQUE (product_id, deleted)
);
```
这里创建了一个带有两个列的复合索引`idx_product_id_deleted`,其中第一个列是`product_id`,第二个列是`deleted`。同时创建了一个复合唯一约束`uc_product_id_deleted`,确保在相同的`product_id`和`deleted`值组合下,不能插入重复的记录。当`deleted`值为`Y`时,可以插入相同的`product_id`值,因为它们的`deleted`值不同。
阅读全文