重新排序非规范化列值

时间:2013-11-30 14:08:21

标签: sql sql-server

我有一个非规范化表格,最多包含8张用户照片:

CREATE TABLE [dbo].[Users] (
  Id int NOT NULL,
  ProfileId int NOT NULL,
  Photo1 int DEFAULT NULL,
  Photo2 int DEFAULT NULL,
  Photo3 int DEFAULT NULL,
  Photo4 int DEFAULT NULL,
  Photo5 int DEFAULT NULL,
  Photo6 int DEFAULT NULL,
  Photo7 int DEFAULT NULL,
  Photo8 int DEFAULT NULL,
  CONSTRAINT [PK_Users_ProfileId_Id] PRIMARY KEY CLUSTERED ([ProfileId], [Id])
)

用户可以更改每张照片的位置(移动它)。我想要实现的是,当用户将照片移动到另一个位置时,必须将此照片保存到其他照片列,其余照片必须重新排序:

如果我将Photo8移动到Photo1,它应该将Photo8保存到Photo1,Photo1到Photo2,Photo2到Photo3 ...

如果我将Photo2移动到Photo4,它应该将Photo2保存到Photo4,Photo3保存到Photo2,Photo4保存到Photo3。

如何使用SQL实现此目的,最好不使用动态生成的SQL(EXEC-Method)。

2 个答案:

答案 0 :(得分:1)

您应该考虑更改数据库设计。例如:

users table
-----------
id           int
profile_id   int
name         varchar
....


photos table
------------
id        int
user_id   int
rank      int

然后用户可以拥有他/她喜欢的照片数量,您只需更改排名即可更改照片的顺序。

然后将照片8设为1,其他将重新排序:

update photos
set rank = case when rank = 8 then 1
                when rank between 1 and 7 then rank + 1
                else rank
           end
where user_id = 1

数据库设计的一个重要规则是当您需要列名中的数字(如photo1,photo2)时,那就很糟糕了。

答案 1 :(得分:0)

我假设您不想更改数据库。考虑在这样的应用程序代码中解决这个问题:

  1. 将PhotoID复制到列表中(显然最多包含8个项目)
  2. 根据需要插入/删除/重新排序(这在大多数语言中都很容易)
  3. 将列表内容复制回列
  4. 步骤1和3是可重复使用的,因此您只需要编写一次。

相关问题