簡體   English   中英

使用其他列值按條件順序更新Sql列

[英]Update Sql column with other column values in order with conditions

我正在嘗試更新我的玩家在桌上的位置。 該表由名稱,id,點和位置組成。

點的默認值為0然后位置將為“ Unranked排名”。

如果兩個用戶的分數相同,那么位置將相同。

演示桌

id  | name | points | position
1   | a    | 0      | Unranked
2   | b    | 120    | 2
3   | c    | 130    | 3
4   | d    | 120    | 1

所需結果應為

id  | name | points | position
1   | a    | 0      | Unranked
2   | b    | 120    | 2
3   | c    | 130    | 1
4   | d    | 120    | 2

查詢將類似於未排序update mytable set position = 'Unranked' Where points = 0我將如何使用點和位置集查詢?

真痛苦 您可以通過子查詢獲得所需的結果,但這在update子句中不太起作用。 select ,您可以執行以下操作:

select t.*,
       (select 1 + count(*)
        from t t2
        where t2.points > 0 and t2.points > t.points
       ) as rank
from t;

您現在可以將其合並到更新中:

update t join
       (select t.*,
               (select 1 + count(*)
                from t t2
                where t2.points > 0 and t2.points > t.points
               ) as new_position
        from t;
       ) tt
       on t.id = tt.id
    set t.position = tt.new_position
    where t.points > 0;

無需將計算出的列position保留在表中。 以下適用於所有版本:

create table tab ( id int, name varchar(1), points int );
insert into tab values
(1,'a',  0),
(2,'b',120),
(3,'c',130),
(4,'d',120);
select t.id, t.name, t.points, 
       ( case when points = 0 then 'Unranked' else t.rnk end ) as position
  from
  (
    select t1.*,  
           @rnk := if(@pnt = points,@rnk,@rnk + 1) rnk,
           @pnt := points
      from tab t1 
     cross join (select @rnk := 0, @pnt := 0 ) t2
      order by points desc
   ) t
 order by t.id;

id  name  points  position
--  ----  ------  --------
1    a      0     Unranked
2    b     120       2
3    c     130       1
4    d     120       2

如果要保留表中的列position ,則可以通過綁定主列id來使用以下update語句:

 update tab tt
    set position = ( select 
                     ( case when points = 0 then 'Unranked' else t.rnk end ) as position
                      from
                      (
                        select t1.*, 
                               @rnk := if(@pnt = points,@rnk,@rnk + 1) rnk,
                               @pnt := points
                          from tab t1 
                         cross join (select @rnk := 0, @pnt := 0 ) t2
                          order by points desc
                       ) t                    
                      where t.id = tt.id );

Rextester演示

如果您的MySQl版本(MySQL 8.x)支持窗口功能,則可能出現以下情況:

SELECT name,
RANK() OVER (
    ORDER BY points DESC
) position
FROM mytable
where points != 0

然后可以像Gordon Linoff的答案一樣將選定的數據加入以進行更新。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM