使用Join更新

时间:2016-11-28 22:13:39

标签: sql sql-server tsql

SourceTable
-----------
Global_id int
Product_id varchar
Category int
Status int


Client
------
Client_id
Global_id
...


References
----------
Client_id
Category int
Status int
...

我正在尝试更新Category表中StatusReferences列的值。要更新的源数据来自以下查询(返回多行)。

select * from SourceTable where Product_id = 'id01234';

然后在Global_id s的上述查询结果中,我可以更新References表。但是,Global_id列不在References表上,而是在Client表上。

如何构造update语句来更新References表?感谢。

2 个答案:

答案 0 :(得分:1)

尝试以下查询:

UPDATE T1
SET T1.Status = T3.Status , T2.Category = T3.Category
FROM References AS T1 INNER JOIN Clients AS T2 on T1.Client_Id = T2.CLient_Id 
INNER JOIN (select * from SourceTable where Product_id = 'id01234') AS T3 ON T2.Global_id = T3.Global_Id

答案 1 :(得分:1)

您可以尝试以下操作。但是,如果一个Product_id可能会为单个Global_id返回多行,则表示一个Global_id可以匹配多个类别和状态。这将导致问题。

UPDATE r SET r.Category=t.Category,r.Status=t.Status 
FROM #References AS r
INNER JOIN #Client AS c ON r.Client_id=c.Client_id
INNER JOIN #SourceTable AS t ON t.Global_id=t.Global_id
WHERE t.Product_id='id01234'

这是一个完整的示例脚本:

CREATE TABLE #SourceTable(Global_id int,Product_id VARCHAR(100),Category int,Status INT)
INSERT INTO #SourceTable 
SELECT 1,'id01234',10,1 union
SELECT 1,'id01235',11,0

CREATE TABLE #Client(Client_id int,Global_id INT)
INSERT INTO #Client
SELECT 100,1 UNION SELECT 200,1

CREATE TABLE #References(Client_id INT,Category INT,Status INT)
INSERT INTO #References(Client_id)
SELECT 100 UNION SELECT 200

UPDATE r SET r.Category=t.Category,r.Status=t.Status 
FROM #References AS r
INNER JOIN #Client AS c ON r.Client_id=c.Client_id
INNER JOIN #SourceTable AS t ON t.Global_id=t.Global_id
WHERE t.Product_id='id01234'

SELECT * FROM #References
Client_id   Category    Status
----------- ----------- -----------
100         10          1
200         10          1