[英]MSsql update column from joint table
I have 2 tables ex. 我有2张桌子。 TABLE1 and TABLE2 表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
what i want is to update TABLE2.SCORE so the values will be TABLE1.value column and the join to be SIZE. 我想要的是更新TABLE2.SCORE,因此值将为TABLE1.value列,联接为SIZE。
OUTPUT:
ID | SIZE | SCORE
1 | MID | 3.0
2 | MID | 3.0
3 | HIGH | 5.0
I tried: Update Table2 set SCORE=(select top(1) VALUE from TABLE1 join TABLE2 on table1.size=table2.size )
however this does not work I get this result: 我试过了: 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
update a
set a.score=b.score
from table2 a join table1 b on a.id=b.id
You can use a JOIN
in the UPDATE
: 您可以在UPDATE
使用JOIN
:
update t2
set t2.score = t1.score
from table2 t2 join
table1 t1
on t2.size = t1.size;
You can also follow your pattern by using a correlated subquery: 您还可以通过使用相关子查询来遵循您的模式:
update table2
set t2.score = (select t1.score from table1 t1 where t1.size = table2.size);
There is no need for another JOIN
in the subquery. 子查询中不需要其他JOIN
。
Try this 尝试这个
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
Demo result : http://rextester.com/VFF59681 演示结果: http : //rextester.com/VFF59681
You don't need to do the JOIN
in subquery
you can directly express it as : 您无需在subquery
执行JOIN
即可将其直接表示为:
update table2
set score = (select top (1) t1.score from table1 t1 where t1.size = table2.size);
You can achieve it like this: 您可以这样实现:
update table2
set table2.SCORE = table1.VALUE
from table2
join table1
on table2.SIZE = table1.SIZE
However, to avoid problems, you will need to make sure table1.SIZE
is unique
. 但是,为避免出现问题,您将需要确保table1.SIZE
是unique
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.