简体   繁体   English

Oracle SQL:插入 SELECT

[英]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 ?是否可以使用select和条件where category_name = 'adventure'所以我得到BOM-001从另一个表获取category_id 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 .请注意, 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:第二:您可以从某处插入您 select 的行:

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';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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