简体   繁体   中英

Oracle SQL: INSERT with SELECT

i have a query like this:

insert into book ('book_id', 'category_id', 'book_name', 'buy_price', 'sell_price') values ('B-001, 'BOM-001', 'Tarzan', 200, 300);

is it possible to get the category_id from another table which is category table using select and condition where category_name = 'adventure' so i get the BOM-001 ? can anyone give me a sample of that query?

thank you

This would look like:

insert into book (book_id, category_id, book_name, buy_price, sell_price)
    select ?, c.category_id, ?, ?, ?
    from category c
    where c.category_name = ?;

The ? are placeholders for your constant values. Note that there are no single quotes around the column names for the insert .

There are two ways to achieve what you want.

First: a single value can always be replaced by a query that returns a single value:

insert into book (book_id, category_id, book_name, buy_price, sell_price)
values ('B-001', 
        (select category_id from category where category_name = 'adventure'),
        'Tarzan',
        200,
        300
       );

Second: You can insert rows you select from somewhere:

insert into book (book_id, category_id, book_name, buy_price, sell_price)
select 'B-001', category_id, 'Tarzan', 200, 300
from category where category_name = 'adventure';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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