Re: problem query ...

Поиск
Список
Период
Сортировка
От Tom Lane
Тема Re: problem query ...
Дата
Msg-id 4065.1012501418@sss.pgh.pa.us
обсуждение исходный текст
Ответ на Re: problem query ...  (John Taylor <postgres@jtresponse.co.uk>)
Список pgsql-novice
John Taylor <postgres@jtresponse.co.uk> writes:
> On Thursday 31 January 2002 17:35, Frank Bax wrote:
>> select mytable.* from mytable, (select id,max(update) as update from
>> mytable group by id) maxes where mytable.id = maxes.id and mytable.update =
>> maxes.update;

> I didn't think of putting the subselect there, I was trying in the
> where clause.  However, I think using distinct on is probably going to
> run faster.

DISTINCT ON will certainly be quicker.  Another point is that the
behavior isn't necessarily exactly the same.  Suppose that id/update
isn't unique.  Frank's query will give you all the rows with the
maximal update value for each id value.  DISTINCT ON will give you
only one of those rows --- one chosen at random, if you just order
by id and update, or you can order by additional columns to determine
which of the possible rows is selected.  So depending on the behavior
you actually want, either way might be more appropriate.

BTW, although I faulted DISTINCT ON for being nonstandard, subselect
in the FROM clause isn't necessarily portable either; it is standard
but a lot of allegedly-SQL DBMSes don't support it (including Postgres
prior to 7.1).  If you wanted to do this in a way that's actually
portable, you might have to create a temp table, do the select max/group
by id into the temp table, and then join the temp table against the
original.  Yech.

            regards, tom lane

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

Предыдущее
От: "Sammer Reinhard J."
Дата:
Сообщение: Re: column headers all in upper-case letters?
Следующее
От: Frank Bax
Дата:
Сообщение: Re: column headers all in upper-case letters?