我有两张桌子。表1和表2
TABLE1 TABLE2
ID | SIZE | VALUE ID | SIZE | SCORE
1 | LOW | 1.0 1 | MID | 3232
2 | MID | 3.0 2 | MID | 2321
3 | HIGH | 5.0 3 | HIGH | 3232
我想要的是更新TABLE2.SCORE,因此值将是TABLE1.value列,连接将是SIZE。
OUTPUT:
ID | SIZE | SCORE
1 | MID | 3.0
2 | MID | 3.0
3 | HIGH | 5.0
我试过了:
Update Table2 set SCORE=(select top(1) VALUE from TABLE1 join TABLE2 on table1.size=table2.size )
但是这不起作用我得到了这个结果:
OUTPUT:
ID | SIZE | SCORE
1 | MID | 3.0
2 | MID | 3.0
3 | HIGH | 3.0 <---- wrong
答案 0 :(得分:2)
update a
set a.score=b.score
from table2 a join table1 b on a.id=b.id
答案 1 :(得分:2)
您可以在JOIN
中使用UPDATE
:
update t2
set t2.score = t1.score
from table2 t2 join
table1 t1
on t2.size = t1.size;
您还可以使用相关子查询来跟踪您的模式:
update table2
set t2.score = (select t1.score from table1 t1 where t1.size = table2.size);
子查询中不需要另一个JOIN
。
答案 2 :(得分:2)
试试这个
DECLARE @TABLE1 AS TABLE(ID INT , SIZE VARCHAR(10) , VALUE decimal(2,1))
INSERT INTO @TABLE1
SELECT 1 , 'LOW' , 1.0 UNION ALL
SELECT 2 , 'MID' , 3.0 UNION ALL
SELECT 3 , 'HIGH' , 5.0
DECLARE @TABLE2 AS TABLE(ID INT , SIZE VARCHAR(10) , SCORE INT)
INSERT INTO @TABLE2
SELECT 1 , 'MID' , 3232 UNION ALL
SELECT 2 , 'MID' , 2321 UNION ALL
SELECT 3 , 'HIGH' , 3232
SELECT * FROM @TABLE2
UPDATE t2
SET SCORE=t1.VALUE
FROM @TABLE2 t2 inner join @TABLE1 t1 On t1.SIZE=t2.SIZE
SELECT ID,SIZE, CAST(SCORE AS DECIMAL(2,1)) AS SCORE
FROM @TABLE2
答案 3 :(得分:1)
您无需在JOIN
中执行subquery
,您可以直接将其表达为:
update table2
set score = (select top (1) t1.score from table1 t1 where t1.size = table2.size);
答案 4 :(得分:1)
你可以这样做:
update table2
set table2.SCORE = table1.VALUE
from table2
join table1
on table2.SIZE = table1.SIZE
但是,为避免出现问题,您需要确保table1.SIZE
为unique
。