MySQL排名条件来自两个表

时间:2015-07-16 11:11:59

标签: mysql conditional-statements ranking

我有两个表:第一个是用户数据(名称:用户),第二个是用户统计信息(名称:users_stats)。下面我把我的排名MySQL查询(使用一个表:users_stats):

SELECT  d.*, c.ranks FROM (
    SELECT sold, @rank:=@rank+1 ranks FROM (
        SELECT DISTINCT a.`sold` FROM users_stats a ORDER BY sold DESC
    ) t, 
    (SELECT @rank:= 0) 
r) c 
INNER JOIN users_stats d ON c.sold = d.sold 
WHERE login = 'XXXXXX'

RESULTS:
LOGIN_1 - 50 SOLD - RANK 1 (ACTIVE) 
LOGIN_2 - 40 SOLD - RANK 2 (ACTIVE) 
LOGIN_3 - 40 SOLD - RANK 2 (ACTIVE)
LOGIN_4 - 30 SOLD - RANK 3 (BLOCKED)
LOGIN_5 - 20 SOLD - RANK 4 (ACTIVE)

我想在此查询帐户中添加活动条件,因为我不希望在非活动或被阻止的人中排名。

我尝试将条件查询:

SELECT  d.*, c.ranks FROM (
    SELECT sold, @rank:=@rank+1 ranks FROM (
        SELECT DISTINCT a.`sold` FROM users_stats a ORDER BY sold DESC
    ) t, 
    (SELECT @rank:= 0) 
r) c 
INNER JOIN users_stats d ON c.sold = d.sold 
WHERE login = 'XXXXXX'  
AND `login` IN (SELECT b.`login` FROM `users` b WHERE b.`active` = 'YES')

...但我跳过排名位置,例如:

RESULTS: 
LOGIN_1 - 50 SOLD - RANK 1 (ACTIVE) 
LOGIN_2 - 40 SOLD - RANK 2 (ACTIVE) 
LOGIN_3 - 40 SOLD - RANK 2 (ACTIVE) 
LOGIN_4 - 20 SOLD - RANK 4 (ACTIVE)

我很高兴有任何线索! :)谢谢!

1 个答案:

答案 0 :(得分:0)

我认为你的查询工作太多了。您不需要在子查询中执行distinct,您可以直接枚举sold值。这需要两个变量和更多逻辑。

在任何情况下,您的问题的答案都是在您选择join值时执行sold。这是一种方法:

  SELECT us.*,
         (@rank := if(@s = sold, @rank + 1,
                      if(@s := sold, 1, 1)
                     )
         ) as rank
  FROM users_stats us JOIN
       users u
       ON us.login = u.login CROSS JOIN 
       (SELECT @rank:= 0, @s := 0) params
 WHERE u.login = 'XXXXXX'
 ORDER BY sold,  DESC