选择要更新的查询

时间:2016-03-26 04:47:32

标签: mysql sql sql-update ranking

我有一个像这样的选择查询

select er.*,
       (@rank := if(@ep = exam_place_id, @rank + 1,
                    if(@ep := exam_place_id, 1, 1) 
                   )
       ) as ranking
from examresults er cross join
     (select @rank := 0, @ep := -1) params
order by exam_place_id,
         point desc;

我想用排名的值更新我的 class_ranking 列,因此我尝试将我的选择查询更改为

      update examresults inner join
(select er.*,
       (@rank := if(@ep = exam_place_id, @rank + 1,
                    if(@ep := exam_place_id, 1, 1) 
                   )
       ) as ranking
from examresults er cross join
     (select @rank := 0, @ep := -1) params
order by exam_place_id,
         point desc
) t3 
ON examresults.O_NO = t3.O_NO
set examresults.class_ranking = t3.ranking

但是我在class_ranking上收到错误的排名,这对于select查询是正确的。

enter image description here

感谢

1 个答案:

答案 0 :(得分:0)

没有样本结构和数据,我无法弄清楚为什么你会得到错误的结果。因为MariaDB ORDER BY in a subselect不起作用 - 我不知道MySQL在这里的表现如何。解决方法是使用大量的LIMIT。但您可以将select语句重写为更新语句:

update examresults er 
cross join (select @rank := 0, @ep := -1) params
set er.class_ranking = 
       (@rank := if(@ep = exam_place_id, @rank + 1,
                    if(@ep := exam_place_id, 1, 1) 
                   )
       )
order by exam_place_id,
         point desc;

更新: UPDATE接缝无法与JOINORDER BY一起使用,因此您需要删除该联接,但会有两个声明:

select 0, 1 into @rank, @ep;

update examresults er 
-- cross join (select @rank := 0, @ep := -1) params
set er.class_ranking = 
       (@rank := if(@ep = exam_place_id, @rank + 1,
                    if(@ep := exam_place_id, 1, 1) 
                   )
       )
order by exam_place_id,
         point desc;

然而,还有另一种方法可以让排名加入表格并计算排名更差或相等的所有行:

select er.*, count(er1.id) as ranking
from examresults er
join examresults er1 
    on  er1.exam_place_id = er.exam_place_id
    and er1.point >= er.point
group by er.id

更新声明就像

update examresults
join (
    select er.*, count(er1.id) as ranking
    from examresults er
    join examresults er1 
        on  er1.exam_place_id = er.exam_place_id
        and er1.point >= er.point
    group by er.id
) t3 ON examresults.O_NO = t3.O_NO
set examresults.class_ranking = t3.ranking