16

我正在使用 mysql 数据库。我知道 postgresql 和 SQL server 支持部分索引。就我而言,我想做这样的事情:

CREATE UNIQUE INDEX myIndex ON myTable (myColumn) where myColumn <> 'myText'

我想创建一个唯一的约束,但如果它是一个特定的文本,它应该允许重复。

我在mysql中找不到直接的方法来做到这一点。但是,是否有解决方法来实现它?

4

2 回答 2

13

过滤后的索引可以用函数索引和CASE表达式来模拟(MySQL 8.0.13 和更新版本):

CREATE TABLE t(id INT PRIMARY KEY, myColumn VARCHAR(100));

-- NULL are not taken into account with `UNIQUE` indexes   
CREATE UNIQUE INDEX myIndex ON t((CASE WHEN myColumn <> 'myText' THEN myColumn END));


-- inserting excluded value twice
INSERT INTO t(id, myColumn) VALUES(1, 'myText'), (2, 'myText');

-- trying to insert different value than excluded twice
INSERT INTO t(id, myColumn) VALUES(3, 'aaaaa');

INSERT INTO t(id, myColumn) VALUES(4, 'aaaaa');
-- Duplicate entry 'aaaaa' for key 'myIndex'

SELECT * FROM t;

db<>小提琴演示

输出:

+-----+----------+
| id  | myColumn |
+-----+----------+
|  1  | myText   |
|  2  | myText   |
|  3  | aaaaa    |
+-----+----------+
于 2019-07-07T06:05:01.060 回答
8

我想只有一种方法可以实现它。您可以在表中添加另一列,在其上创建索引并创建触发器或在存储过程中插入/更新以使用以下条件填充此列:

if value = 'myText' then put null
otherwise put value

希望能帮助到你

于 2011-10-18T09:10:34.370 回答