SQL ordered filtering from multiple columns -
i have table below, being used both mysql , sqlite, sorted columns a, b, c in ascending order:
# | | b | c -------------------------- 0 | 40 | 55 | blue 1 | 60 | 65 | red 2 | 60 | 65 | rose 3 | 60 | 65 | yellow 4 | 80 | 21 | green 5 | 85 | 12 | blue
i want figure out "next" row after given row. example, if i'm looking @ row #2:
a=60, b=65, c="rose"
i want able figure out row #3 next 1 (i don't have # ids use in case).
my naive approach this:
select * table (a >= 60 , b >= 65 , c > "rose") or (a >= 60 , b > 65) or (a > 60) order a, b, c asc limit 1
is there better way this?
thanks
exclusive branches
only slight change... think >=
can =
:
select * table (a = 60 , b = 65 , c > "rose") or (a = 60 , b > 65) or (a > 60) order a, b, c asc limit 1
ids don't help
you can add "ids" using rank or row_number (probably rank because group duplicates).
// emulate rank in mysql select @rankinc := @rankinc + 1 rank a, b, c table, (select @currank := 0) r group a, b, c order a, b, c;
...but couldn't think of query uses that's better 1 posted. i think approach pretty direct , lean.
// best effort using rank select nr.a, nr.b, nr.c ranksubquery r inner join ranksubquery nr on r.rank + 1 = nr.rank r.a = 60 , r.b = 65 , r.c = "rose"
Comments
Post a Comment