mysql - Sorting result with absolute placement -
http://sqlfiddle.com/#!2/1840d/1
i have table of ids , places, possible rows set @ specified places?
to get
id place 5 (null) 3 2 4 (null) 6 4 2 (null) 1 (null)
instead of
id place 6 4 5 (null) 4 (null) 3 2 2 (null) 1 (null)
for data means have row place = 2 second row in result , row place = 4 fourth in result, while other rows cover them in original order.
answer
select * records order field(id, 5,3,4,6,2,1)
is nice , funny, wrong.
select case when nullid null id else nullid end id, tofilltable.place ( select case when id null @placeholder := @placeholder + 1 else null end placeholder , r.* ( select @row := @row + 1 row records t1, (select @row := 0) t2 ) s inner join (select @placeholder := 0) t12 left outer join records r on s.row = r.place order row ) tofilltable left outer join ( select @row1 := @row1 + 1 nullrowplace, t1.id nullid records t1, (select @row1 := 0) t2 place null order t1.id desc ) nullplacetable on tofilltable.placeholder = nullplacetable.nullrowplace
the first query output result :
tofilltable placeholder id place 1 (null) (null) (null) 3 2 2 (null) (null) (null) 6 4 3 (null) (null) 4 (null) (null)
it gives id when place given on right row, , give counter named placeholder on row place null.
the second query:
nullplacetable nullplaceholder idnull 1 5 2 4 3 2 4 1
it gives rank of row when place null.
the join of 2 gives expected!
reference:
Comments
Post a Comment