Postgres表约束使用group-by [英] Postgres table constraint using group-by

查看:190
本文介绍了Postgres表约束使用group-by的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Postgres表如下:

 类别单位默认单位
----- ----------------------------------
货币USD True
货币EURO False
货币AUS False
长度公里True
长度Mile False
长度Foot False
长度英寸False
大量公斤True



我想设置一个表约束,使每个类别只能有一个默认单位。



这可以在约束中使用Group By完成,也许?

解决方案

 在表(类别,default_unit)上创建唯一索引idx_table(category,default_unit)
其中default_unit;


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?

解决方案

You can create a unique partial index:

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

这篇关于Postgres表约束使用group-by的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆