当我需要从连接在一起的两个表和另一个表中插入时,如何在sql中使用insert into from

时间:2018-10-06 12:17:32

标签: sql oracle

INSERT INTO reserve ( 
    branch_code, 
    bc_id, 
    reserve_date_time_placed, 
    bor_no )
SELECT b.branch_code, 
       c.bc_id, 
       TO_DATE('2018-09-20, 4:00 P.M.', 'YYYY-MM-DD, HH:MI P.M.'), 
       w.bor_no FROM borrower w
FROM borrower w, book_copy c
     JOIN branch b on c.branch_code = b.branch_code
WHERE b.branch_contact_no = '8888888883'
AND c.book_call_no = '005.74 C822D 2018'
AND w.fname = 'Ada';

我试图将分别来自借方表的bor_no和来自book_copy表的其他信息与分支表一起插入到储备表中。

所以我想更好地解释我的问题,我尝试从(book_copy与分支连接)和(借款人)插入储备表中。但是借书者和book_copy没有关系。

borrower table is created like below.

    CREATE TABLE borrower (
    bor_no         NUMBER(6) NOT NULL,
    bor_fname      VARCHAR2(59) NOT NULL,
    bor_lname      VARCHAR2(50) NOT NULL,
    bor_street     VARCHAR2(80) NOT NULL,
    bor_suburb     VARCHAR2(50) NOT NULL,
    bor_postcode   CHAR(4) NOT NULL,
    branch_code    NUMBER(2) NOT NULL
);

2 个答案:

答案 0 :(得分:1)

一个错误是您有多个FROM子句。尝试像这样编写查询:

INSERT INTO reserve (branch_code, bc_id, reserve_date_time_placed, bor_no )
    SELECT b.branch_code, bc.bc_id, 
           TO_DATE('2018-09-20, 4:00 P.M.', 'YYYY-MM-DD, HH:MI P.M.'), 
           w.bor_no 
    FROM book_copy bc JOIN
         branch b 
         ON bc.branch_code = b.branch_code JOIN
         borrower w
         ON w.fname = 'Ada'
    WHERE b.branch_contact_no = '8888888883' AND
          bc.book_call_no = '005.74 C822D 2018';

请注意,这对所有 JOIN使用正确的JOIN语法。 FROM子句中没有逗号。

答案 1 :(得分:0)

在示例中,请确保您两次“来自borower”。

之后,您可以使用insert into ...选择...

INSERT INTO reserve ( 
branch_code, 
bc_id, 
reserve_date_time_placed, 
bor_no ) 
SELECT b.branch_code, 
       c.bc_id, 
       TO_DATE('2018-09-20, 4:00 P.M.', 'YYYY-MM-DD, HH:MI P.M.'), 
       w.bor_no 
FROM  book_copy c
     JOIN branch b on c.branch_code = b.branch_code
     JOIN bororwer w on c ..... = w. .... 
WHERE b.branch_contact_no = '8888888883'
AND c.book_call_no = '005.74 C822D 2018'
AND w.fname = 'Ada';

您的错误是什么?

编辑: 您只能像这样从book_Copy和分支执行插入操作:

INSERT INTO reserve ( 
branch_code, 
bc_id, 
reserve_date_time_placed, 
bor_no ) 
SELECT b.branch_code, 
       c.bc_id, 
       TO_DATE('2018-09-20, 4:00 P.M.', 'YYYY-MM-DD, HH:MI P.M.'), 
       w.bor_no 
FROM  book_copy c
     JOIN branch b on c.branch_code = b.branch_code
      WHERE b.branch_contact_no = '8888888883'
AND c.book_call_no = '005.74 C822D 2018'

在那之后,将borrower_id放入变量

select @borower_id from borrower where fname = 'Ada' 

然后更新储备金:

update reserve set borrower_id = @borrower_id 
where book_call_no = .... and branch_contact = .. ...