Re: [SQL] Finding the "most recent" rows

Поиск
Список
Период
Сортировка
От Tom Lane
Тема Re: [SQL] Finding the "most recent" rows
Дата
Msg-id 21889.924884968@sss.pgh.pa.us
обсуждение исходный текст
Ответ на Re: [SQL] Finding the "most recent" rows  (Brook Milligan <brook@trillium.NMSU.Edu>)
Ответы Re: [SQL] Finding the "most recent" rows
Список pgsql-sql
Brook Milligan <brook@trillium.NMSU.Edu> writes:
>    Tom Lane wrote:
>> 
>> SELECT DISTINCT ON place * FROM table ORDER BY place, time DESC;
>> 
>> might do the right thing.  It *seems* to select the first row for each
>> value of place.  I've never seen a spec for this feature, however, so
>> I'm not sure if it's reliable or not...

> Cool idea.  Is DISTINCT guarranteed to choose the first row that
> matches or can it choose any row?

I dunno, that's why I said I was unsure that this method was reliable.
By experimentation it seems that Postgres' DISTINCT code works that way,
but I have no idea whether the SQL spec mandates it or allows any row
within a group to be chosen.

I recall now that when I first heard of "SELECT DISTINCT ON field"
I objected that the results weren't well-defined (since it's not clear
how DISTINCT will choose which tuple to return).  It might be that the
SQL spec requires the first tuple to be chosen for each value of
"field", which would allow the user to control the results by inserting
a preceding ORDER BY step --- or skip the ORDER BY, if he doesn't really
care which tuple he gets.  That'd actually be a pretty cool design.
Anyone have an SQL spec handy to check it?
        regards, tom lane


В списке pgsql-sql по дате отправления:

Предыдущее
От: Tom Lane
Дата:
Сообщение: Re: [SQL] Finding the "most recent" rows
Следующее
От: Bruce Momjian
Дата:
Сообщение: Re: [HACKERS] Re: [SQL] Finding the "most recent" rows