问题
using MySQL I need to fill a column with the position in the list using ORDER BY.
I saw this post : mysql-get-row-position-in-order-by
The problem with the above post (2nd solution), is that it, when it encounters the same values in the list, the position is the same, but 'gaps' appear for the next record(s). I want the positions to be consecutive.
Let's say I have a list like this :
id val
A 3
B 5
C 2
D 6
E 1
F 8
G 2
H 6
I would like to get an ordered output with a position column like this :
id val pos
E 1 1
C 2 2
G 2 2
A 3 3
B 5 4
D 6 5
H 6 5
F 8 6
回答1:
select id,val,
@pos := if(@prev<>val,@pos+1,@pos) as pos,
@prev := val as val
from table,(select @pos:=0,@prev:='') as r order by val
I agree with other advices that it would be better to do this at application level.
回答2:
What about this:
SELECT `id`,
(SELECT COUNT(DISTINCT `val`) + 1
FROM `table`
WHERE `val` < `outer`.`val`) AS `pos`,
`val`
FROM `table` `outer`
ORDER BY `val`
Just've taken my answer from that thread and changed it a little.
But as @reko_t mentioned in the comments - I personally vote for doing this in programming language.
来源:https://stackoverflow.com/questions/5857036/mysql-concecutive-order-positions