问题
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