php - Does ORDER BY apply before or after DISTINCT? -
in mysql query, when using distinct
option, order by
apply after duplicates removed? if not, there way make so? think it's causing issues code.
edit:
here's more information what's causing problem. understand that, @ first glance, order not important, since dealing duplicate rows. however, not entirely case, since using inner join
sort rows.
say have table of forum threads, containing data:
+----+--------+-------------+ | id | userid | title | +----+--------+-------------+ | 1 | 1 | information | | 2 | 1 | faq | | 3 | 2 | support | +----+--------+-------------+
i have set of posts in table this:
+----+----------+--------+---------+ | id | threadid | userid | content | +----+----------+--------+---------+ | 1 | 1 | 1 | lorem | | 2 | 1 | 2 | ipsum | | 3 | 2 | 2 | test | | 4 | 3 | 1 | foo | | 5 | 2 | 3 | bar | | 6 | 3 | 5 | bob | | 7 | 1 | 2 | joe | +----+----------+--------+---------+
i using following mysql query threads, sort them based on latest post (assuming posts higher ids more recent:
select t.* threads t inner join posts p on t.id = p.threadid order p.id desc
this works, , generates this:
+----+--------+-------------+ | id | userid | title | +----+--------+-------------+ | 1 | 1 | information | | 3 | 2 | support | | 2 | 1 | faq | | 3 | 2 | support | | 2 | 1 | faq | | 1 | 1 | information | | 1 | 1 | information | +----+--------+-------------+
however, can see, information correct, there duplicate rows. i'd remove such duplicates, used select distinct
instead. however, yielded following:
+----+--------+-------------+ | id | userid | title | +----+--------+-------------+ | 3 | 2 | support | | 2 | 1 | faq | | 1 | 1 | information | +----+--------+-------------+
this wrong, since "information" thread should on top. seem using distinct
causes duplicates removed top bottom, final rows left. causes issues in sorting.
is case, or analyzing things incorrectly?
two things understand:
generally speaking, resultsets unordered unless specify
order by
clause; extent specify non-strict order (i.e.order by
on non-unique columns), order in records equal under ordering appear within resultset undefined.i suspect may specifying such non-strict order, root of problems: ensure ordering strict specifying
order by
on set of columns sufficient uniquely identify each record care final position in resultset.distinct
may usegroup by
, causes results ordered grouped columns; is,select distinct a, b, c t
produce resultset appears thoughorder a, b, c
has been applied. again, specifying sufficiently strict order meet needs override effect.
following update, bearing in mind point #2 above, clear effect of grouping results achieve distinct
makes impossible order non-grouped column p.id
; instead, want:
select t.* threads t inner join posts p on t.id = p.threadid group t.id order max(p.id) desc
Comments
Post a Comment