更新表中条件位于另一个表中的行范围

时间:2014-11-26 10:30:46

标签: sql

示例:

表1

invoice line article price
1       1    pen       10
1       2    mouse     11
1       3    paper     15
2       1    ...       25
2       2    ...       80
2       3    ...     
2       4    ....

表2

invoice    date
1          2014-01-03 00:00:00.0000
2          2014-05-12 00:00:00.0000
3          2014-06-17 00:00:00.0000

如何仅在发票日期为例如11月份的行上更新价格

我知道我必须使用联接,但我已经加入此表以便在同一查询中执行其他操作:

UPDATE invoicelines
SET invoicelines.netprice = ART.price
FROM invoicelines IL INNER JOIN items ITM
ON IL.item = ITM.item

我想用指定的日期更新invoicelines,但这个日期在另一个表中,情况类似于第一个例子

3 个答案:

答案 0 :(得分:0)

update table1
set    price = price + 10
from   table1 t1 join table2 t2 on t1.invoice = t2.invoice
where  month(t2.date) = 11

答案 1 :(得分:0)

关于"我知道我必须使用加入":不,你不必加入。当条件在另一个表中时,您通常会使用EXISTS或IN。

update table1
set price = ...
where invoice in 
(
  select invoice 
  from table2
  where month(`date`) = 11
);

或者:

update table1
set price = ...
where exists 
(
  select * 
  from table2 
  where month(table2.`date`) = 11 
  and table2.invoice = table1.invoice
);

您忘了为自己的dbms命名。日期函数主要是特定于dbms的,因此可以使用或不使用MONTH函数。

答案 2 :(得分:0)

我解决了这个

UPDATE Invoicelines
SET Invoicelines.NetPrice = ART.Price
FROM Invoicelines BR INNER JOIN Items ART join InvoiceHead bt on month(bt.docdate)=11 
ON BR.Item = ART.Item
where BR.sheetNumber=bt.sheetNumber