Unique Constraint with conditions in MYSQL

后端 未结 5 1794
心在旅途
心在旅途 2020-12-18 09:35

In postgres we have a constraint defined that essentially allows us to limit the number of entries in a table with a certain value to one. We created this constraint:

5条回答
  •  半阙折子戏
    2020-12-18 09:41

    I never use MySQL but maybe you can create an index like this:

    CREATE UNIQUE INDEX list$default$uk ON list_group ((CASE WHEN list_type='default' THEN NULL ELSE visitor_uid END));
    

    Explanation: A unique index should not care about NULL values. Therefore, make sure the index expression returns NULL for every row where list_type <> 'default'.

提交回复
热议问题