简体   繁体   English

使用 if 逻辑 oracle sql 检查约束

[英]check constraint with if logic oracle sql

Is there a way to use if logic in an oracle sql check constraints?有没有办法在oracle sql检查约束中使用if逻辑?

This is my pseudo table:这是我的伪表:

create table child
(
    name,
    behaviour,
    treat,
);

Now what i want is that if the behaviour of child = 'bad' then treat != 'lollies' .现在我想的是,如果behaviour的孩子= 'bad'treat != 'lollies'

Sometimes it is easier to express using NOT to define what is not allowed:有时使用 NOT 来定义不允许的内容更容易表达:

CHECK (NOT (behaviour = 'bad' AND treat = 'lollies'))

... which means same as: ...这意味着相同:

CHECK (behaviour != 'bad' OR treat != 'lollies')

It is easy to get this wrong, as other answers have shown!正如其他答案所示,这很容易出错!

ALTER TABLE child 
  ADD CONSTRAINT bad_behaviour_CK 
    CHECK (NOT (behaviour = 'bad' AND treat = 'lollies')) ;

Tesed in SQL-FiddleSQL-Fiddle 中测试

If you have learned propositional logic before, we can apply it in this situation and explain how the top voted answer is derived.如果你之前学过命题逻辑,我们可以在这种情况下应用它,并解释如何推导出最高投票的答案。

We let A be the proposition of behavior = 'bad' and B be the proposition of treat != 'lollies' .我们让Abehavior = 'bad'的命题, Btreat != 'lollies'的命题。 The statement of "If behavior = 'bad' , then treat != 'lollies' " can be written as " AB ". “If behavior = 'bad' , treat != 'lollies' ”的语句可以写成“ AB ”。

Note that " AB " is logically equivalent to "¬ AB " (¬ means NOT and ∨ means OR).请注意,“ AB ”在逻辑上等同于“¬ AB ”(¬ 表示非,∨ 表示或)。 Therefore, we can translate the statement "¬ AB " back to " behavior != 'bad' OR 'treat != 'lollies' ".因此,我们可以将语句“¬ AB ”翻译回“ behavior != 'bad' OR 'treat != 'lollies' ”。

In terms of SQL, we can write this as:在 SQL 方面,我们可以这样写:

CHECK (behaviour <> 'bad' OR treat <> 'lollies')

This is equivalent to:这相当于:

CHECK (NOT (behaviour = 'bad' AND treat = 'lollies'))

Try this试试这个

create table children ( 
        childname VARCHAR2(50), behaviour VARCHAR2(50),treats VARCHAR2(50),
        constraint behave_treat check (behaviour = 'bad' AND treats != 'lollies')
        ) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM