Postgres table constraint using group-by

牧云@^-^@ 提交于 2019-12-11 06:44:54

问题


I have a Postgres table that looks like this:

Category     Unit          Default Unit
---------------------------------------
Currency     USD           True
Currency     EURO          False
Currency     AUS           False
Length       Kilometer     True
Length       Mile          False
Length       Foot          False
Length       Inch          False
Mass         Kilogram      True

I want to set a table constraint so that there can be only one 'Default Unit' per Category.

Can this be done using Group By in a constraint, perhaps?


回答1:


You can create a unique partial index:

create unique index idx_table(category, default_unit) on table(category, default_unit)
    where default_unit;


来源:https://stackoverflow.com/questions/27476736/postgres-table-constraint-using-group-by

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