我有这些表
用户
+----------+---------------+
| id_users | usr_email |
+----------+---------------+
| 1 | a@domain.com |
| 2 | b@domain.com |
| 3 | c@domain.com |
| 4 | d@domain.com |
| 5 | e@domain.com |
+----------+---------------+
RANKING
+-------------+-----------+----------+
| id_ranking | id_users | points |
+-------------+-----------+----------+
| 50 | 1 | 27 | //3rd
| 51 | 2 | 55 | //1st
| 52 | 3 | 9 | //5th
| 53 | 4 | 14 | //4th
| 54 | 5 | 38 | //2nd
+-------------+-----------+----------+
我想退出用户的数据以及它的排名位置,通过电子邮件过滤。例如,如果我想要邮件信息 c@domain.com 我应该
+----------+--------|---------------+
| id_users | points | rank_position |
+----------+--------|---------------+
| 3 | 9 | 5 |
+----------+--------|---------------+
我发现这条返回排名位置的查询
SELECT x.id_users, x.position
FROM (
SELECT t1.id_ranking, t1.id_users, @rownum := @rownum + 1 AS position
FROM ranking t1
JOIN (SELECT @rownum := 0) r ORDER BY t1.points desc
) x
WHERE x.id_users = 3
但我无法在旧查询中使用它
select u.*, r.points
from users u
left join ranking r on r.id_users = u.id_users
where u.usr_email = 'c@domain.com'
我的尝试
select u.*, r.points, p.*
from users u
left join ranking r on r.id_users = u.id_users,
(SELECT x.id_users, x.position
FROM (
SELECT t1.id_ranking, t1.id_users, @rownum := @rownum + 1 AS position
FROM ranking t1
JOIN (SELECT @rownum := 0) r ORDER BY t1.points desc
) x
WHERE x.id_users = u.id_users) p
where u.usr_email = 'c@domain.com'
任何帮助?
答案 0 :(得分:1)
您错过了join
条件。但是,ranking
的外部联接也不是必需的。你可以记住"子查询中的点:
select u.*, r.points, r.position
from users u left join
(select r.*, @rownum := @rownum + 1 AS position
from ranking r CROSS JOIN
(SELECT @rownum := 0) r
order by r.points desc
) r
ON r.id_users = u.id_users
where u.usr_email = 'c@domain.com'
答案 1 :(得分:1)
select u.id_users,
r.points,
count(ifnull(r2.id_users, 0)) + 1 as rank_position
from users u
join ranking r
on u.id_users = r.id_users
left join ranking r2
on r2.points > r.points
where u.usr_email = 'c@domain.com'
group by u.id_users, r.points
小提琴: http://sqlfiddle.com/#!2/1444e8/1/0
这不是一个变量,而是计算点数比给定用户多的用户数,然后加一个。这是根据点数计算其等级的等效方法。