Re: complicated query (newbie..)

From: Sam Mason <sam(at)samason(dot)me(dot)uk>
To: pgsql-general(at)postgresql(dot)org
Subject: Re: complicated query (newbie..)
Date: 2009-04-09 16:36:45
Message-ID: 20090409163645.GR12225@frubble.xen.chris-lamb.co.uk
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Thu, Apr 09, 2009 at 06:08:04PM +0200, Marcin Krol wrote:
> What I'm trying to accomplish is producing list of hosts available
> within a specified timeframe.
>
> What I have is a table of hosts, table of reservations (containing id,
> start_date and end_date) and an association table reservation_hosts.
>
> I need a list of hosts, with accompanying reservations fulfilling
> certain (date-related) conditions.
>
> But there are two twists:
>
> - if host has reservation(s), but those do not fulfill the date
> conditions (the host is not available within a specified timeframe), the
> host obviously should NOT be listed
>
> - if host has no reservations at all, it obviously is available, so it
> should be listed

I think the following should do what you want.

SELECT h.id, r.id, r.start_date, r.end_date
FROM hosts h
LEFT JOIN (reservation_hosts m INNER JOIN reservation r
ON m.reservation_id = r.id
AND (r.start_date,r.end_date) OVERLAPS (${window_start},${window_end})
ON h.id = m.host_id
WHERE h.id NOT IN (
SELECT m.host_id
FROM reservation r, reservation_hosts m
WHERE r.id = m.reservation_id
AND m.host_id IS NOT NULL
AND (r.start_date,r.end_date) OVERLAPS (${requested_start},${requested_end})
ORDER BY h.id, r.start_date)

The formatting is somewhat grim, but I think it should do what you want.

--
Sam http://samason.me.uk/

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Sam Mason 2009-04-09 16:40:10 Re: ON condition in LEFT OUTER JOIN doesn't work?!
Previous Message Marcin Krol 2009-04-09 16:34:27 ON condition in LEFT OUTER JOIN doesn't work?!