Workaround in mysql for partial Index or filtered Index?

假如想象 提交于 2019-12-01 14:41:01

问题


I am using mysql db. I know postgresql and SQL server supports partial Indexing. In my case I want to do something like this:

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

I want to create a unique constraint but it should allow duplicates if it is a particular text.

I couldn't find a direct way to do this in mysql. But, is there a workaround to achieve it?


回答1:


I suppose there is only one way to achieve it. You can add another column to your table, create index on it and create trigger or do insert/update inside your stored procedures to fill this column using following condition:

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

Hope it helps




回答2:


Filtered indexes could be emulated with function indexes and CASE expression(MySQL 8.0.13 and newer):

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<>fiddle demo

Output:

+-----+----------+
| id  | myColumn |
+-----+----------+
|  1  | myText   |
|  2  | myText   |
|  3  | aaaaa    |
+-----+----------+


来源:https://stackoverflow.com/questions/7804565/workaround-in-mysql-for-partial-index-or-filtered-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!