sql - postgres: How to prevent INSERT in a special case -


I found a table 'Foo' that looks like

  id. NAME ------ + ---------------------------- 123 | Pirates of the Caribbean 254 | NinjasAreCoolerThanPirates  

and a second table 'Bar'

  SID | ID | Made Dropped ------ + ------ + ------------ + ----------- 9871 | 123 | 03.24.2009 | 03.26.2009 9872 | 123 | 04.02.2009 | There is a reference (foreign key) on   

bar.id foo.id .

Now I want to prevent this, you can insert a new record for 'Bar', when there is a record with the same ID and that bar is on the bar.Dropped on the sale.

Then, when 'bar' looks upwards

  INSERT ('9873', '123', '07.224.2009 ', NULL) in bar values;  

should be restricted, but enter

  in bar values ​​('9873', '254', '07.224.2009 ', NULL) ;  

should be allowed (because there is no 'open' bar-record for 'Ninja's cooler' city).

How do I do this? I hope my problem is clear and someone can help me.

Hmm, it should just be enough to make a unique index.

Create unique index ix_open_bar on bar (id, dropped); Of course, this will also have the effect that you can not drop twice a day (unless dropped a timestamp which reduces the risk)

Actually, I noticed that PostGrace has been given support for partial index:

  create unique index ix_open_bar on the id (id) where it has been dropped;  Updates:  After some tests, unique obstacles are not applied to zero values, but partial indexes will still work.  

And if you do not want to use partial index, it can also work: Create a unique index ix_open_bar on bar (id, collage (dropped) , 'tap')); However, while using organized, you need to have the same datatype on them (so if a timestamp has been dropped, then you have to change the 'null' to the timestamp value instead).

P>

Comments

Popular posts from this blog

c# - ListView onScroll event -

PHP - get image from byte array -

Linux Terminal Problem with Non-Canonical Terminal I/O app -