Skip to content

Instantly share code, notes, and snippets.

@aonurdemir
Last active November 10, 2018 16:23
Show Gist options
  • Select an option

  • Save aonurdemir/68c1e4a8eed82311f2b701e8ec1f5f52 to your computer and use it in GitHub Desktop.

Select an option

Save aonurdemir/68c1e4a8eed82311f2b701e8ec1f5f52 to your computer and use it in GitHub Desktop.
Mysql user variables and conditional where clauses
#query orders users wrt their points. Then chooses 11 users regarding below
#if searched user's rank <=9, get full 11.
#else get the searched user and 2 others below and above him/her and merge with the first 6 users.
select
rank,
`current_user`,
total
from (
select
@rank := IF(@current_user = fullboard.user_id, 1, @rank + 1) as rank,
@current_user := fullboard.user_id as `current_user`,
@pivot_rank := CASE
when @current_user = @searched_user
then @rank
else @pivot_rank
end as pivot_rank,
fullboard.total
from (select
user_id,
SUM(t.value) as total
from user_points up, gamification_point_types t
where up.point_type_key = t.`key`
group by up.user_id
order by total desc) as fullboard
CROSS JOIN (SELECT #this is for initializing the variables
@rank := 0,
@pivot_rank := 9,
@searched_user := 3358) vars
) as processedQuery
#conditional where clauses
where (@pivot_rank > 9 and (processedQuery.rank > @pivot_rank - 3 and processedQuery.rank < @pivot_rank + 3) or
processedQuery.rank <= 6)
or (@pivot_rank <= 9 and processedQuery.rank <= 11)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment