在表的更新操作中,在很多情况下需要在表达式中引用要更新的表以外的数据。象sql server提供了update的from 子句,可以将要更新的表与其它的数据源连接起来。虽然只能对一个表进行更新,但是通过将要更新的表与其它的数据源连接起来,就可以在update的表达式中引用要更新的表以外的其它数据。
例如:
UPDATE Table2
SET Table2.ColB = Table2.ColB + Table1.ColB
FROM Table2
INNER JOIN Table1
ON (Table2.ColA = Table1.ColA);
实际更新的操作是在要更新的表上进行的,而不是在from子句所形成的新的结果集上进行的。
Oracle没有update from语法,可以通过两种写法实现同样的功能:
1:子查询UPDATE A SET A.NAME=(SELECT B.NAME FROM B WHERE B.ID=A.ID),本查询要根据具体情况看看是否变通成如下
(1)单列
UPDATE A
SET A.NAME=(SELECT B.NAME FROM B WHERE B.ID=A.ID)
WHERE A.ID IN (SELECT ID FROM B);
(2)多列
UPDATE order_rollup
SET(qty,price)=(SELECT SUM(qty),SUM(price) FROM order_lines WHERE customer_id='KOHL' )
WHERE cust_id='KOHL' AND order_period=TO_DATE('01-Oct-2000')
源码
update "SHOP_GOODS_DATE_copy" copy set(HOTEL_INFO_NAME,
TITLE,
UP_DOWN_STATUS,HOTEL_ID)=(
SELECT
HOTEL_INFO_NAME,
SGHB.TITLE,
UP_DOWN_STATUS,
SGHB.HOTEL_ID
FROM SHOP_GOODS_HOTEL_INFO SGHI
LEFT JOIN(
SELECT
TITLE,
HOTEL_BODY_ID,
HOTEL_ID
FROM SHOP_GOODS_HOTEL_B
)SGHB ON SGHI.HOTEL_BODY_ID=SGHB.HOTEL_BODY_ID
WHERE SGHI.HOTEL_INFO_ID=copy.HOTEL_INFO_ID
)
2:利用视图来做
UPDATE (SELECT A.NAME ANAME,B.NAME BNAME FROM A,B WHERE A.ID=B.ID)
SET ANAME=BNAME;
例如:
UPDATE tablea a
SET a.fieldforupdate = (SELECT b.fieldsource FROM tableb b WHERE a.keyfield = b.keyfield)
WHERE EXISTS (SELECT b.fieldsource FROM tableb b WHERE a.keyfield = b.keyfield)
select * from (
select HOTEL_INFO_NAME,TITLE,"DATE", DATAS from
( select D.HOTEL_INFO_NAME,D.TITLE,D."DATE", D.INFO_PRICE||','||D.TOTEL_NUMBER||','||D.GOODS_NUMBER DATAS from
( SELECT DATE_ID,
"DATE",
GOODS_NUMBER,
INFO_PRICE,
CTIME,
UTIME,
HOTEL_INFO_ID,
TOTEL_NUMBER,
HOTEL_INFO_NAME,
TITLE,
UP_DOWN_STATUS,
HOTEL_ID
FROM "SHOP_GOODS_DATE_copy"
where HOTEL_ID='UWFNJ1K2O3160UTCIEQK'
AND "DATE">='2018-04-24'
AND "DATE"<='2018-04-30'
order by "DATE" )D
)) pivot (max(DATAS) for "DATE" in ('2018-04-24' date1, '2018-04-25' date2,'2018-04-26' date3, '2018-04-27' date4, '2018-04-28' date5, '2018-04-29' date6, '2018-04-30' date7));
有三点需要注意:
- 对于一个给定的a.keyfield的值,SELECT b.fieldsource FROM tableb b WHERE a.keyfield = b.keyfield 的值只能是一个唯一值,不能是多值。
- 在绝大多数情况下,最后面的where EXISTS子句是重要的,否则将得到错误的结果。
- 对于视图更新的限制:
如果视图基于多个表的连接,那么用户更新(update)视图记录的能力将受到限制。除非update只涉及一个表且视图列中包含了被更新的表的整个主键,否则不能更新视图的基表。