I have two tables, “event” and “event_exception”. Table “event” has a (boolean) column “regular” that indicates whether the event is to occur regularly every year or not. Table “event_exception” has a column “event_id”, a column “year” and a (boolean) column “occurs”.
The data is to be interpreted this way:
- Some events occur regularly every year, but sometimes they exceptionally don’t, which is being encoded by an “event” row with “event.regular == True” and an “event_exception” row with “event_exception.occurs == False” for every year where the event exceptionally is omitted.
- Some events don’t occur regularly, but sometimes they exceptionally do. This is being encoded by an “event” row with “event.regular == False” and an “event_exception” row with “event_exception.occurs == True” for every year where the event exceptionally occurs.
How can I write a query that matches all events that will occur this year?
My guess was something like
session.query(Event, EventException).filter(Event.id==EventException.event_id)
.filter(EventException.year==current_year).
filter(or_(
and_(Event.regular==1, EventException.occurs==0, having(count(EventException)==0)),
and_(Event.regular==0, EventException==1, having(count(EventException)>0)
))
, but I’m not sure if the having clause can be used within an and_.
You can’t use
HAVINGwithoutGROUP BY. Anyway, neither of them is necessary in this case, what is needed isEXISTS. Assuming you already have a SQLAlchemy relationship defined forEvent.exceptions, the following expression should work:and generate SQL like the following:
EDIT: the first condition should use
NOT EXISTSinstead