SQL insert into select 用法

    SQL insert into select 用法

    一张存在的表,插入的新数据来源别的表时,可以使用insert into select语法。

    1、两种语法

    1、表数据

    user表

    id name age

    1 test 10

    2 test1 20

    3 test2 14

    4 test3 16

    user_copy表

    user_copy 表结构与 user 表一样,只不过数据为空。

    address 表

    id city address user_id

    1 广州市 天河区 2

    2 肇庆市 端州区 1

    3 汕头市 朝阳区 1

    4 肇庆市 鼎湖区 3

    5 汕头市 从化区 3

    6 广州市 白云区 2

    address与user属于多对一的关系。

    2、语法1

    如果两表的结构完全相同,可以直接使用以下的简易语法。

    insert into 表名2 select * from 表名1 where 条件

    例子

    上文 user 表 与user_copy表结构一样,因此例子如下:

    insert into user_copy select * from user u where u.id in(1,2)

    id 为1、2的数据便成功插入到user_copy表中。

    结果如下:

    3、语法2

    如果只希望插入希望的列,或者特定的列指定为常量,语法如下

    insert into 表名2(列名1, 列名2, 列名3) select 返回值1,返回值2,常量 as 返回值3 from 表名1,表名3,表名4 where 条件

    注意:返回值要与表2的列名一一对应。

    例子

    向user_copy插入特定的name和age, age指定为15,例子如下:

    insert into user_copy(name, age)

    select u.name as name, 15 as age

    from user u, address a

    where u.id = a.user_id and a.address = '从化区'

    结果如下:

    根据需求选择对应的语法。