【问题标题】:Unique null index唯一空索引
【发布时间】:2016-04-07 10:05:30
【问题描述】:

我有一张桌子

CREATE TABLE mandantconfigentity
(
  id bigint NOT NULL,
  currentlegalversionnumber integer NOT NULL DEFAULT 5,
  belongsto_userid character varying(255)
)

如何创建一个唯一索引,以确保该表只能有一行,其中 belongsto_userid 为空?

这不起作用:

CREATE UNIQUE INDEX unique_mandantconfig_for_null_belongsto 
    ON mandantconfigentity (1) 
 WHERE (belongsto_userid IS NULL);

【问题讨论】:

    标签: sql postgresql unique-constraint


    【解决方案1】:
    CREATE UNIQUE INDEX unique_mandantconfig_for_null_belongsto 
        ON mandantconfigentity ((1)) 
    WHERE (belongsto_userid IS NULL);
    

    那么它做了什么 - 它在表达式上创建了一个部分索引:对于 belongsto_userid IS NULL 所在的每一行,它明确地具有固定值 1

    CREATE INDEX 命令的语法通常需要在索引表达式周围加上括号,如第二个示例所示。当表达式只是一个函数调用时,括号可以省略,如第一个示例所示。

    所以语法需要额外的括号。

    参考资料:

    【讨论】:

      【解决方案2】:

      创建索引的代码需要列名:

      CREATE UNIQUE INDEX unique_mandantconfig_for_null_belongsto 
          ON mandantconfigentity (id) 
      WHERE (belongsto_userid IS NULL);
      

      【讨论】:

      • 如何保证最多只有一行的belongsto_userid等于NULLsqlfiddle.com/#!15/3c614/1
      • 这个不行,它保证了id只在userid为null的时候出现一次
      猜你喜欢
      • 2014-08-13
      • 2013-02-02
      • 1970-01-01
      • 2016-07-19
      • 2012-07-03
      • 1970-01-01
      • 1970-01-01
      • 2016-04-14
      • 2015-12-29
      相关资源
      最近更新 更多