我有一个一对多的表,其中包含这些用户的ID和特征。 我想将一个用户的设置复制到另一个用户。
userid trait onoff
------ ----- -----
1 1 on
1 2 on
1 3 on
1 4 on
2 1 off
2 2 off
2 3 off
2 4 off
所以我想将用户1的onoff值复制到2,以便user2在完成后将所有内容都打开。
更新表设置onoff =(从userid = 1的表中选择onoff)userid = 2
这是基本的想法,但显然不起作用。我想我希望服务器根据相关子查询进行思考,但外部部分不是查询,而是更新。
这是否可以一步到位?
答案 0 :(得分:0)
试试这个,userid = 2将获得useid = 1值:
UPDATE u2
SET onoff=u1.onoff
FROM YourTable u2
INNER JOIN YourTable u1 ON u2.trait=u1.trait
WHERE u2.userid=2 AND u1.userid=1
完整的SQL Server 2005+示例:
DECLARE @YourTable table (userid int,trait int, onoff varchar(3))
INSERT INTO @YourTable VALUES (1, 1, 'on')
INSERT INTO @YourTable VALUES (1, 2, 'on')
INSERT INTO @YourTable VALUES (1, 3, 'on')
INSERT INTO @YourTable VALUES (1, 4, 'on')
INSERT INTO @YourTable VALUES (2, 1, 'off')
INSERT INTO @YourTable VALUES (2, 2, 'off')
INSERT INTO @YourTable VALUES (2, 3, 'off')
INSERT INTO @YourTable VALUES (2, 4, 'off')
select * from @YourTable order by userid,trait
UPDATE u2
SET onoff=u1.onoff
FROM @YourTable u2
INNER JOIN @YourTable u1 ON u2.trait=u1.trait
WHERE u2.userid=2 AND u1.userid=1
select * from @YourTable order by userid,trait
输出
userid trait onoff
----------- ----------- -----
1 1 on
1 2 on
1 3 on
1 4 on
2 1 off
2 2 off
2 3 off
2 4 off
(8 row(s) affected)
(4 row(s) affected)
userid trait onoff
----------- ----------- -----
1 1 on
1 2 on
1 3 on
1 4 on
2 1 on
2 2 on
2 3 on
2 4 on
(8 row(s) affected)
答案 1 :(得分:0)
MERGE
在SQL-99标准中引入,在SQL:2003中进行了改进,并由多个供应商实现(和扩展)(例如SQL Server 2008,Oracle,postgreSQL):
MERGE INTO YourTable
USING (
SELECT userid, trait, onoff
FROM YourTable
WHERE userid = 2
) AS S
ON YourTable.userid = 1
AND S.trait = YourTable.trait
WHEN MATCHED THEN
UPDATE
SET onoff = S.onoff
WHEN NOT MATCHED THEN
INSERT (userid, trait, onoff)
VALUES (userid, trait, onoff);