简体   繁体   English

添加检查约束不工作SQL

[英]Add Check Constraint not working SQL

I need to add a constraint to a table such that column ab is always greater than column h. 我需要在表中添加一个约束,使列ab始终大于列h。 I have tried 我努力了

ALTER TABLE batting
ADD constraint possibleHits check (ab>h);

But that returns 但那会回来

ERROR:  check constraint "possiblehits" is violated by some row

********** Error **********

ERROR: check constraint "possiblehits" is violated by some row
SQL state: 23514

as an error. 作为一个错误。

I have run 我跑了

select * from batting where ab<h

and it returns no rows. 它不返回任何行。

Any ideas on what i'm doing wrong? 关于我做错什么的任何想法? or is there a way to do something like add 或者有办法做一些像添加

NOT VALID

to the statement so that it will not enforce the constraint on existing rows? 语句,以便它不会对现有行施加约束? I know that that works in mysql but in postgres it only works on keys. 我知道这在mysql中有效但在postgres中它只适用于键。

EDIT: 编辑:

So as was pointed out there are instances where ab = h however is there a way to exclude existing rows from the constraint? 因此,正如所指出的,在某些情况下ab = h,但是有没有办法从约束中排除现有行?

You should check for values where ab=h. 你应该检查ab = h的值。 I'm sure you'll find your problem. 我相信你会发现你的问题。

See below for one example of it working. 请参阅下面的一个工作示例。

sqlfiddle demo sqlfiddle演示

If you want column ab is always greater than column h, then you need to delete those 6000 rows where ab=h, if don't want to delete those 6000 rows, you can try this. 如果你想列ab总是大于列h,那么你需要删除那些ab = h的6000行,如果不想删除这6000行,你可以试试这个。

 ALTER TABLE batting
 ADD constraint possibleHits check(ab>=h);

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

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