Re: Help with a subselect inside a view - Mailing list pgsql-general

From Bill Moseley
Subject Re: Help with a subselect inside a view
Date
Msg-id 20050825150126.GA14559@hank.org
Whole thread Raw
In response to Re: Help with a subselect inside a view  (David Fetter <david@fetter.org>)
Responses Re: Help with a subselect inside a view
Re: Help with a subselect inside a view
List pgsql-general
Hi David,

On Thu, Aug 25, 2005 at 01:22:02AM -0700, David Fetter wrote:
> This sounds like a case for PostgreSQL's nifty DISTINCT ON functionality.
>
> http://www.postgresql.org/docs/current/static/sql-select.html#SQL-DISTINCT

   The DISTINCT ON expression(s) must match the leftmost ORDER BY
   expression(s). The ORDER BY clause will normally contain additional
   expression(s) that determine the desired precedence of rows within
   each DISTINCT ON group.

I read that and thought it wasn't a drop-in replacement for my code
due to the leftmost ORDER BY requirement.  But, it seems to work even
if that requirement is not met.

Perhaps I not understanding the wording above?  Or is Postgresql
adding in the order automatically?

My original VIEWS with duplicates:

    DROP VIEW cl;
    CREATE VIEW cl  (id, class_time, instructor)
        AS
            SELECT class.id, class.class_time, person.first_name
              FROM class, instructors, person
             WHERE instructors.person = person.id
               AND class.id = instructors.class;


     select * from cl where id = 555;
     id  |       class_time       | instructor
    -----+------------------------+------------
     555 | 2005-09-30 09:00:00-07 | Cheryl
     555 | 2005-09-30 09:00:00-07 | Bob
    (2 rows)


And with DISTINCT ON():

    DROP VIEW cl;
    CREATE VIEW cl  (id, class_time, instructor)
        AS
            SELECT DISTINCT ON(class.id)
                   class.id, class.class_time, person.first_name
              FROM class, instructors, person
             WHERE instructors.person = person.id
               AND class.id = instructors.class;



     select * from cl where id = 555;
     id  |       class_time       | instructor
    -----+------------------------+------------
     555 | 2005-09-30 09:00:00-07 | Cheryl
    (1 row)


Here where the leftmost ORDER BY doesn't match the DISTINCT ON, which I thought
was not possible:


    select * from cl where class_time > now() order by instructor limit 3;
     id  |       class_time       | instructor
    -----+------------------------+------------
     544 | 2005-08-31 09:00:00-07 | Cheryl
     555 | 2005-09-30 09:00:00-07 | Cheryl
     737 | 2005-08-30 09:00:00-07 | Cynthia


--
Bill Moseley
moseley@hank.org


pgsql-general by date:

Previous
From: Brad Nicholson
Date:
Subject: Re: Postgresql replication
Next
From: "Julio Cesar"
Date:
Subject: SOCKET Conection on Windwos 2003 vs PostgreSQL 8.0.1