PostgreSQL数据库中的条件索引

时间:2016-07-10 06:14:34

标签: database postgresql relational-database database-indexes

我正在使用Windows 10 Pro x64上的PostgreSQL数据库版本9.5。

在我的数据库中,我有两个整数列,一个用于所有数量,一个用于可用数量。 我基本上想要的是,如果所有数量都小于可用数量,则阻止插入或更新,因此我创建了这个索引:

FAILED: ParseException line 1:106 mismatched input ',' expecting StringLiteral near 'BY' in table row format's field separator

问题是索引不起作用,我可以使用包含所有小于可用数量的数量值的行插入到表中。我刚尝试了这个查询,它成功返回。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
  <NumberPicker
        android:theme="@android:style/Theme.Holo.Light"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/agePicker" />
</LinearLayout>

1 个答案:

答案 0 :(得分:1)

如果要在表上应用某些业务逻辑,则需要使用约束,而不是索引:

ALTER TABLE "Items" 
ADD CONSTRAINT "Items_Avialability_Check" 
CHECK ("AllQuantity" > "AvailableQuantity");

有了这个约束,如果您尝试在OP中声明的相同插入,您将收到以下错误:

  

错误:关系“Items”的新行违反了检查约束“Items_Avialability_Check”   详细信息:失败行包含(1,some_item,1234567891234,15,20,20,40,2016-08-08,2016-09-22,null,null)。