使用查询结果更新表

时间:2013-03-21 11:48:41

标签: sql oracle sql-update

我正在尝试将查询结果添加到现有表的列中。 到目前为止,下面的查询计算CAR_PRICE并显示该值。但是,我想将此值添加到car_price列中的CAR_PAYMENT_TBL

下面的create table命令显示了相关的表以及它们之间的关系。是否可以更新CAR_PRICE中的CAR_PAYMENT_TBL值?

SELECT C.TICKET_NO, 
            C.REG_ID,
            C.BOOKING_ID,
            (R.END_DATE-R.START_DATE) AS DAYS_STAYED,
            (R.END_DATE-R.START_DATE)*5 AS CAR_PRICE
            FROM CAR_TBL C
            LEFT JOIN
            ROOM_TBL R
            ON C.BOOKING_ID = R.BOOKING_ID;

TABLE SCHEMA:

CREATE TABLE CAR_PAYMENT_TBL
(
    TICKET_NO INT NOT NULL PRIMARY KEY,
    CAR_PRICE NUMERIC(5,2) 
);

CREATE TABLE CAR_TBL
(
    REG_ID VARCHAR2(7) NOT NULL PRIMARY KEY,
    TICKET_NO INT NOT NULL references CAR_PAYMENT_TBL(TICKET_NO),
    BOOKING_ID INT NOT NULL references BOOKING_TBL(BOOKING_ID)
);

CREATE TABLE ROOM_TBL
(  
    STAY_NO INT NOT NULL PRIMARY KEY,
    ROOM_NO VARCHAR2(4) NOT NULL references ROOM_DETAILS_TBL(ROOM_NO),
    START_DATE DATE NOT NULL,
    END_DATE DATE NOT NULL,
    BOOKING_ID INT NOT NULL references BOOKING_TBL(BOOKING_ID)
);

2 个答案:

答案 0 :(得分:4)

您无法在Oracle的UPDATE语句中引用其他表 - 使用子查询或MERGE语句:

  UPDATE CAR_PAYMENT_TBL
  SET CAR_PRICE =
  (select (ROOM_TBL.END_DATE - ROOM_TBL.START_DATE)*5 from room_tbl where ... )
  WHERE CAR_PAYMENT_TBL.TICKET_NO = &TICKET_NO;    

您还必须为子查询提供合理的WHERE子句(假设& TICKET_NO实际上是绑定变量,而不是两个表的连接条件)。

答案 1 :(得分:0)

如果您想根据CAR_PAYMENT_TBL的值更新ROOM_TBL的所有记录 然后

UPDATE CAR_PAYMENT_TBL
SET CAR_PRICE = (select (ROOM_TBL.END_DATE – ROOM_TBL.START_DATE)*5
FROM ROOM_TBL WHERE CAR_PAYMENT_TBL.TICKET_NO = ROOM_TBL.TICKET_NO)

如果您只想更新CAR_PAYMENT_TBL的特定记录,那么

UPDATE CAR_PAYMENT_TBL
SET CAR_PRICE = (select (ROOM_TBL.END_DATE – ROOM_TBL.START_DATE)*5
FROM ROOM_TBL WHERE CAR_PAYMENT_TBL.TICKET_NO = ROOM_TBL.TICKET_NO)
where CAR_PAYMENT_TBL = &ticket_num;