MySQL sorting group-by results -
MySQL sorting group-by results -
i have next tables structure:
table_1
id title ------------ 155 item1 156 item2 157 item3
table_2
id model ------------ 155 100 156 100 157 200
table_3
id cid ------------ 155 5 156 5 157 5
i want grouping results model (from table_2) and create sure returns highest id (order id
descending).
i have tried following, order by clause doesn't seem work:
select a.id, b.model table_1 inner bring together table_2 b on b.id = a.id inner bring together table_3 c on c.id = a.id c.cid = 5 grouping b.model order a.id desc
what doing wrong?
select max(a.id), b.model table_1 inner bring together table_2 b on b.id = a.id inner bring together table_3 c on c.id = a.id c.cid = 5 grouping b.model order max(a.id) desc
demo here: http://sqlfiddle.com/#!9/afb0b/2
the reason works while initial effort did not, field not nowadays in group by
clause, or not used in aggregate function (such max
), have indeterminate value (ie, mysql engine makes no guarantees value grouping get).
mysql grouping handling
the server free take value each group, unless same, values chosen indeterminate.
in fact, mysql 1 of few (only?) sql databases allow set non aggregated, non grouped field in select clause without erroring.
mysql group-by sql-order-by
Comments
Post a Comment