我的数据库中有这些表:
USER_ACCOUNT
USER_CHARACTER
USER_ACCOUNT列:AccountID,Character1,Character2,Character3
USER_CHARACTER列:它包含特定字符的所有数据 单独但在这种特定情况下我们需要列UserID和 SpecialPoints。
那么,如何通过提供character1,character2 and character3 from USER_ACCOUNT
抓住所有AccountID
并检查其中哪一个>50000 SpecialPoints from USER_CHARACTER
?
如果发现其中一个字符为>50000 SpecialPoints
,则更新特定字符并删除-50000 SpecialPoints
。
我将在我的php脚本上创建两个检查但我仍然坚持创建实际的查询。
我正在使用 MSSQL Server 2005
答案 0 :(得分:0)
好吧,我会抓住它,希望我理解这些问题,但更有可能提供帮助澄清的基础。
注意:我假设USER_ACCOUNT.Character1例如是USER_CHARACTER中的某个FK。应该是。
有几种方法可以帮助您入门。
首先是一些样本数据:
CREATE TABLE USER_ACCOUNT (AccountID INT, Character1 INT,Character2 INT,Character3 INT)
CREATE TABLE USER_CHARACTER (CharacterID INT, SpecialPoints INT)
GO
INSERT INTO USER_ACCOUNT VALUES (1,10,20,30),(2,40,50,60)
INSERT INTO USER_CHARACTER VALUES (10,10000),(20,20000),(30,30000),(40,40000),(50,50000),(60,60000)
GO
选项1将多次加入。
SELECT Character1
,c1.SpecialPoints
,CASE WHEN c1.SpecialPoints > 50000 THEN 1 ELSE 0 END Character1_50000PlusPoints
,Character2
,c2.SpecialPoints
,CASE WHEN c2.SpecialPoints > 50000 THEN 1 ELSE 0 END Character2_50000PlusPoints
,Character3
,c3.SpecialPoints
,CASE WHEN c2.SpecialPoints > 50000 THEN 1 ELSE 0 END Character3_50000PlusPoints
FROM USER_ACCOUNT a
LEFT JOIN USER_CHARACTER c1 ON a.Character1 = c1.CharacterID
LEFT JOIN USER_CHARACTER c2 ON a.Character2 = c2.CharacterID
LEFT JOIN USER_CHARACTER c3 ON a.Character3 = c3.CharacterID
GO
选项2将使用UNION
WITH cte AS (
SELECT AccountID
,CharacterID
,SpecialPoints
FROM USER_ACCOUNT a
INNER JOIN
USER_CHARACTER b ON a.Character1 = b.CharacterID
UNION ALL
SELECT AccountID
,CharacterID
,SpecialPoints
FROM USER_ACCOUNT a
INNER JOIN
USER_CHARACTER b ON a.Character2 = b.CharacterID
UNION ALL
SELECT AccountID
,CharacterID
,SpecialPoints
FROM USER_ACCOUNT a
INNER JOIN
USER_CHARACTER b ON a.Character3 = b.CharacterID
)
SELECT *
FROM cte
WHERE SpecialPoints > 50000