我在我的数据库中创建了两个视图,每个视图都包含由'br_engagement'在不同时间段内排序的人员列表。我想计算从旧时期到新时期的等级变化。我认为如果我可以在视图中存储变量,这将是很容易的,但是我面临着如何执行查询的挑战,我计算排名的变化时,我只能在{{找到的会话变量中获取它{3}}
这是我能够为新时期创造的前10名的视图:
+---------+----------------------+
| name | total_br_engagements |
+---------+----------------------+
| Person1 | 97553 |
| Person2 | 73576 |
| Person3 | 15245 |
+---------+----------------------+
为了添加排名,我会SELECT @rank := @rank +1 AS rank, name, total_br_engagements
FROM (SELECT * FROM top10current) t1, (SELECT @rank :=0)t2
现在的问题是如何从一个视图(top10old)到一个新视图(top10current)找到排名的变化。我的第一次尝试是:
select @rank:=@rank+1 as rank, old.oldrank, (old.oldrank-rank), new.name, new.total_br_engagements
from ((select name, total_br_engagements from top10current) t1, (select @rank:=0) t2) new
left join (
SELECT @rn:=@rn+1 as `oldrank`, name, side, party, total_br_posts, total_br_engagements
from (select name, side, party, total_br_posts, total_br_engagements from top10old) t01, (select @rn:=0) t02) old
on new.name=old.name
但是在'新左连接(SELECT @rn:= @ rn + 1为oldrank
,名称'附近出现错误。
有更简单的方法可以做到这一点,还是我走在正确的轨道上?
更新: 我修改了代码以使用new_rank作为我当前前十名的名称,但我得到了同样的错误。我还在第二个表中删除了一些不必要的变量名。这是新代码:
select @rank:=@rank+1 as rank, old.oldrank, (old.oldrank-rank), new_rank.name, new_rank.total_br_engagements
from (
(select name, total_br_engagements from top10current) t1, (select @rank:=0) t2) new_rank
left join (
SELECT @rn:=@rn+1 as `oldrank`, name, side, party, total_br_posts, total_br_engagements
from (select name, total_br_engagements from top10old) t01, (select @rn:=0) t02) old
on new_rank.name=old.name
答案 0 :(得分:0)
这是我对您的SQL代码的最好尝试,如果我错了,请不要咬T_T
SELECT @rank := @rank + 1 AS `rank`,
old.oldrank AS `oldrank`,
old.oldrank - @rank AS `rankchange`,
new.name AS `name`,
new.total_br_engagements AS `total_br_engagements`
FROM (
(
SELECT name,
total_br_engagements
FROM top10current) AS t1,
(
SELECT @rank := 0) AS new)
LEFT JOIN
(
SELECT @rn := @rn + 1 AS `oldrank`,
`t2`.`name`,
`t2`.`side`,
`t2`.`party`,
`t2`.`total_br_posts`,
`t2`.`total_br_engagements`
FROM (
SELECT `name`,
`side`,
`party`,
`total_br_posts`,
`total_br_engagements`
FROM top10old) AS t2,
(
SELECT @rn := 0) AS old
) AS t3
ON `new`.`name` = `old`.`name`;
答案 1 :(得分:0)
基于@LFlare的回答。
SELECT @rank := @rank + 1 AS `rank`,
old.oldrank AS `oldrank`,
(old.oldrank- @rank) as `change`,
`new`.name AS `name`,
`new`.total_br_engagements AS `total_br_engagements`
FROM (
(
SELECT name,
total_br_engagements
FROM top10current) AS `new`,
(
SELECT @rank := 0) AS t1)
LEFT JOIN
(
SELECT @rn := @rn + 1 AS `oldrank`,
`old`.`name`,
`old`.`total_br_engagements`
FROM (
SELECT `name`,
`total_br_engagements`
FROM top10old) AS old2,
(
SELECT @rn := 0) AS t2
) AS old
ON `new`.`name` = `old`.`name`