繁体   English   中英

用于更新WHERE条件来自另一个表的列的SQL代码

[英]SQL code for updating a column where the WHERE condition is from another table

在SQL Server 2012中,我有两个表: WINE_TYPEWINE

WINE_TYPE是父表, wtCode是主键( WINE外键)。

我正在尝试执行将酒的价格( winePrice )更新50美分或0.50的代码。 美中不足的是...我的WHERE条件是从父表(我只需要由铅阿曼达·麦克菲制作葡萄酒(wtLeadFirst='Amanda', wtLeadLast='McPhee')将增加50美分)。

内部联接似乎在这里不起作用。 救命?

您可以使用UPDATE ... FROM语法更新具有JOIN条件的表:

UPDATE WINE
SET WINE.WinePrice = WINE.WinePrice + 0.5
FROM
    WINE
INNER JOIN
    WINE_TYPE ON WINE.wtCode = WINE_TYPE.wtCode
WHERE
    WINE_TYPE.wtLeadFirst='Amanda' AND WINE_TYPE.wtLeadLast='McPhee'

Update + Exists

使用Exists运算符检查父表中是否存在wtLeadFirst='Amanda'wtLeadLast='McPhee'

update W
Set Wineprice = x + Wineprice 
from Wine W 
where exists (select 1 
              from wine_type WT 
              where W.wtCode =WT.code 
              and Wt.wtLeadFirst='Amanda' 
              and Wt.wtLeadLast='McPhee' )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM