带有Regex的Postgresql中的条件检查约束

时间:2017-12-02 00:15:03

标签: sql database postgresql

我正在尝试在postgresql中创建一个条件检查约束。当a_type为'a'时,我希望b只包含数字。当a_type不是'a'时,我希望b包含任何字符。我怎么做到这一点?我现在有这个:

编辑: 我认为这应该有效。

CONSTRAINT test CHECK (a_type <> 'a' AND b ~* '^.$') OR (a_type = 'a' AND b ~* '^[0-9]+$')

1 个答案:

答案 0 :(得分:1)

a_type <> 'a'

时,您不必使用正则表达式
check (a_type <> 'a' or a_type = 'a' and b ~* '^[0-9]+$')