Insert into … values ( SELECT … FROM … )

前端 未结 26 2485
我在风中等你
我在风中等你 2020-11-21 05:40

I am trying to INSERT INTO a table using the input from another table. Although this is entirely feasible for many database engines, I always seem to struggle t

26条回答
  •  醉酒成梦
    2020-11-21 06:18

    Two approaches for insert into with select sub-query.

    1. With SELECT subquery returning results with One row.
    2. With SELECT subquery returning results with Multiple rows.

    1. Approach for With SELECT subquery returning results with one row.

    INSERT INTO  (, , ) 
    VALUES ('DUMMY1', (SELECT  FROM  ),'DUMMY2');
    

    In this case, it assumes SELECT Sub-query returns only one row of result based on WHERE condition or SQL aggregate functions like SUM, MAX, AVG etc. Otherwise it will throw error

    2. Approach for With SELECT subquery returning results with multiple rows.

    INSERT INTO  (, , ) 
    SELECT 'DUMMY1', , 'DUMMY2' FROM ;
    

    The second approach will work for both the cases.

提交回复
热议问题