我有像这样的表结构
GameID Player1 Player2 Player3 Player4 Player5 conrti_P1 Contri_P2 Conrti_P3 Contri_P4 Contri_P5
1 1 2 3 4 5 0 0 0 0 0
2 2 1 5 3 4 0 0 0 0 0
Player1到Player5列包含玩家ID。 Contri_p1到Contri_p5列包含它们的点值(最初为0)。现在我想更新玩家的积分。比方说,我想在gameID = 1中更新玩家id = 4的点数。玩家ID的位置每次都不固定。我需要搜索和更新。
我该怎么做?
答案 0 :(得分:3)
我不会试图想出一些聪明的(阅读错综复杂的)方法,试图将您的更新塞进当前的设计中,但会改变表格的设计。
BEGIN TRAN
CREATE TABLE Games (GameID INT PRIMARY KEY)
CREATE TABLE Players (PlayerID INT PRIMARY KEY)
CREATE TABLE PlayersGames (GameID INT, PlayerID INT, Position INT, conrti INT)
INSERT INTO Games VALUES (1), (2)
INSERT INTO Players VALUES (1), (2), (3), (4), (5)
INSERT INTO PlayersGames VALUES (1,1,1,0), (1,2,2,0), (1,3,3,0), (1,4,4,0), (1,5,5,0), (2,2,1,0), (2,1,2,0), (2,5,3,0), (2,3,4,0), (2,4,5,0)
ROLLBACK TRAN
现在您的UPDATE
可以像
UPDATE PlayersGames SET contri = @YourValue WHERE PlayerID = 4 AND GameID = 1
修改强>
对于completenes,整个脚本(包括根据您的问题显示结果)可能如下所示
BEGIN TRAN
CREATE TABLE dbo.Games (GameID INT PRIMARY KEY)
CREATE TABLE dbo.Players (PlayerID INT PRIMARY KEY)
CREATE TABLE dbo.PlayersGames (GameID INT, PlayerID INT, Position INT, contri INT)
ALTER TABLE dbo.PlayersGames ADD CONSTRAINT FK_PLAYERSGAMES_PLAYERS FOREIGN KEY (PlayerID) REFERENCES dbo.Players(PlayerID)
ALTER TABLE dbo.PlayersGames ADD CONSTRAINT FK_PLAYERSGAMES_GAMES FOREIGN KEY (GameID) REFERENCES dbo.Games(GameID)
INSERT INTO Games VALUES (1), (2)
INSERT INTO Players VALUES (1), (2), (3), (4), (5)
INSERT INTO PlayersGames VALUES (1,1,1,0), (1,2,2,3), (1,3,3,0), (1,4,4,0), (1,5,5,0), (2,2,1,0), (2,1,2,0), (2,5,3,0), (2,3,4,0), (2,4,5,0)
SELECT GameID
, Player1 = MIN(CASE WHEN Position = 1 THEN PlayerID ELSE NULL END)
, Player2 = MIN(CASE WHEN Position = 2 THEN PlayerID ELSE NULL END)
, Player3 = MIN(CASE WHEN Position = 3 THEN PlayerID ELSE NULL END)
, Player4 = MIN(CASE WHEN Position = 4 THEN PlayerID ELSE NULL END)
, Player5 = MIN(CASE WHEN Position = 5 THEN PlayerID ELSE NULL END)
, contri_P1 = MIN(CASE WHEN Position = 1 THEN contri ELSE NULL END)
, contri_P2 = MIN(CASE WHEN Position = 2 THEN contri ELSE NULL END)
, contri_P3 = MIN(CASE WHEN Position = 3 THEN contri ELSE NULL END)
, contri_P4 = MIN(CASE WHEN Position = 4 THEN contri ELSE NULL END)
, contri_P5 = MIN(CASE WHEN Position = 5 THEN contri ELSE NULL END)
FROM PlayersGames
GROUP BY
GameID
ROLLBACK TRAN