SQL can I have a “conditionally unique” constraint on a table?

后端 未结 5 738
时光说笑
时光说笑 2020-12-17 18:03

I\'ve had this come up a couple times in my career, and none of my local peers seems to be able to answer it. Say I have a table that has a \"Description\" field which is a

5条回答
  •  温柔的废话
    2020-12-17 18:24

    I'm not entirely aware of your intended use or your tables, but you could try using a one to one relationship. Split out this "sometimes" unique column into a new table, create the UNIQUE index on that column in the new table and FK back to the original table using the original tables PK. Only have a row in this new table when the "unique" data is supposed to exist.

    OLD tables:

    TableA
    ID    pk
    Col1  sometimes unique
    Col...
    

    NEW tables:

    TableA
    ID
    Col...
    
    TableB
    ID   PK, FK to TableA.ID
    Col1 unique index
    

提交回复
热议问题