Re: A challenge for the SQL gurus out there...

From: "Merlin Moncure" <mmoncure(at)gmail(dot)com>
To: "Gregory Stark" <stark(at)enterprisedb(dot)com>
Cc: "Uwe C(dot) Schroeder" <uwe(at)oss4u(dot)com>, pgsql-general(at)postgresql(dot)org
Subject: Re: A challenge for the SQL gurus out there...
Date: 2008-09-09 01:50:58
Message-ID: b42b73150809081850i7f74b7paa87f435ba8c8770@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Mon, Sep 8, 2008 at 9:49 PM, Merlin Moncure <mmoncure(at)gmail(dot)com> wrote:
> On Sun, Sep 7, 2008 at 6:09 AM, Gregory Stark <stark(at)enterprisedb(dot)com> wrote:
>> "Uwe C. Schroeder" <uwe(at)oss4u(dot)com> writes:
>>
>>> I want to get a list looking like
>>>
>>> forum id thread_id post_id
>>> 1 6 443
>>> 2 9 123
>>> 3 3 557
>> ...
>>> It all boils down to me not being able to come up with a query that gives me
>>> the latest post per forum_id.
>>
>> In a situation like this I would probably denormalize the tables slightly by
>> adding a form_id key to the individual posts. That would make it hard to ever
>> move a thread from one forum to another, though not impossible, but would help
>> in this case as well as any other time you want to do an operation on all
>> posts in a forum regardless of thread.
>
> <sql guru hat on>
>
> select f.*,
> (
> select (t,
> (
> select p from post p
> where p.thread_id = t.thread_id
> order by post_id desc limit 1
> ))
> from thread t
> where forum_id = f.forum_id
> order by thread_id desc limit 1
> ) as threadpost
> from forum f;
>
> :-)
>
> 'thread post' is a nested composite, ((thread), post).
>
> The above will pretty much guarantee a fast query unless the number of
> forums is large. To pull out the composite fields, wrap in a subquery
> or (better yet) fire up libpqtypes.

oh, and I assumed id order corresponds to date order...should have
mentioned that, and I had forum.id as forum_id, which it should have
been in the first place.

merlin

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Tom Lane 2008-09-09 01:51:06 Re: ERROR: cache lookup failed for relation
Previous Message Merlin Moncure 2008-09-09 01:49:23 Re: A challenge for the SQL gurus out there...