1

考虑一个包含以下列的表:

ID, Name, Rank

数据如下:

100, John, 1
200, Steve, 2
300, Mike, 3
400, Ben, 4
500, Jake, 5

等级是独一无二的。

如果我想给 Ben 2 的排名并相应地更新其余部分,那么更新表格的最佳方法是什么,以便我最终得到

100, John, 1
400, Ben, 2
200, Steve, 3
300, Mike, 4
500, Jake, 5

有没有比将 Ben 的等级更改为 2 并更新他的新旧等级之间的每一行更聪明的方法呢?

4

4 回答 4

2

这是另一种方法。这将避免重复键问题(假设您对 Rank 有唯一约束)。如果等级低于当前等级,则更新为工作。

DECLARE @ID int, @NewRank int, @CurrentRank int, @LowRank int, @HighRank int
SET @ID=400
SET @NEWRANK=2

SELECT @CurrentRank = Rank FROM MyTable WHERE Id = @ID
SET @LowRank = CASE WHEN @NewRank < @CurrentRank THEN @NewRank ELSE @CurrentRank END
SET @HighRank = CASE WHEN @NewRank < @CurrentRank THEN @CurrentRank ELSE @NewRank END

UPDATE MyTable SET Rank = -Rank WHERE Rank BETWEEN @LowRank AND @HighRank

UPDATE MyTable SET Rank = @NewRank WHERE ID = @ID

UPDATE MyTable SET Rank = 
    CASE 
    WHEN @NewRank < @CurrentRank THEN  -Rank + 1
    ELSE -Rank - 1
    END
WHERE Rank < 0
于 2012-06-18T13:15:04.913 回答
1

If you want to be unnecessarily fancy about it (or have other reasons to do it this way,) and you can plan on just updating the rank of the single row being moved with a single update query, you can use a trigger to force the other rows to update. This would be done as follows:

CREATE OR REPLACE TRIGGER [dbo].[tr_RankChange]
  ON [dbo].[table_name]  Before UPDATE AS 
  BEGIN 
    Update [dbo].[table_name] Set Rank = Rank + 1 Where rank >= New.Rank
    Update [dbo].[table_name] Set Rank = Rank - 1 Where rank >= Old.Rank
  END

I basically wanted to point out that it can be done thing way, not recommend doing it. It is not recommended if you're not familiar with all the other logic that wil lbe applied to the table; if this will be a large scale project with other things going on, you may want to be very careful due to the possible complexity of triggers.

于 2012-06-18T13:33:31.607 回答
1

由于有一些来回,这就是我将如何做到这一点(使用 SQL Server 表示法):

SELECT @CurrentRank = Rank FROM TableName WHERE Id = @SelectedId

UPDATE TableName
SET Rank= 
CASE
    WHEN Id = @SelectedId THEN @NewSelectedRank
    WHEN @NewSelectedRank < @CurrentRank 
        AND Rank >= @NewSelectedRank AND Rank < @CurrentRank
    THEN Rank = Rank + 1
    WHEN @NewSelectedRank > @CurrentRank 
        AND Rank <= @NewSelectedRank AND Rank > @CurrentRank
    THEN Rank = Rank - 1
END
于 2012-06-18T13:10:36.490 回答
1

是否可以根据您可以订购的其他一些列动态计算 yoru 排名?如果是这样,那么您可以使用某些 RDBMS 中的 ROW_NUMBER 函数来相应地计算和更新您的排名。

如果不是,另一种方法(一种作弊)是使用小数作为您的排名,并为 Ben 分配 1.5 的值 :) 这是假设您没有直接从数据库中显示排名。

于 2012-06-18T12:53:17.897 回答