insert into table (a,b,c) select

Posted 香吧香

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了insert into table (a,b,c) select相关的知识,希望对你有一定的参考价值。

本文为博主原创,转载请注明出处:

       在项目中,需要统计数据,从基础表中的数据进行统计,并插入到汇总 表中,

(1)语句形式为:Insert into Table2(field1,field2,...) select value1,value2,... from Table1

或者:Insert into Table2 select  *  from Table1

注意:(1)要求目标表Table2必须存在,并且字段field,field2...也必须存在

(2)注意Table2的主键约束,如果Table2有主键而且不为空,则 field1, field2...中必须包括主键

(3)注意语法,不要加values,和插入一条数据的sql混了,不要写成:

Insert into Table2(field1,field2,...) values (select value1,value2,... from Table1)

应用实例展示:

 <insert id="addMonthStatistics" parameterType="com.statistics.model.MonthStatistics">
        INSERT INTO tbl_statistics_month(month,livePlayCount,vodPlayCount,liveFlow,vodFlow,storeSpace,storeResidueSpace)
        SELECT DATE_FORMAT(#{month}, %Y%m) AS month, SUM(t.livePlayCount) AS livePlayCount, SUM(t.vodPlayCount) AS vodPlayCount, SUM(t.liveFlow) AS liveFlow, SUM(t.vodFlow) AS vodFlow
            , SUM(t.storeSpace) AS storeSpace, SUM(t.storeResidueSpace) AS storeResidueSpace
        FROM (
            SELECT CASE u.playerType WHEN 1 THEN u.num ELSE 0 END AS livePlayCount, CASE u.playerType WHEN 2 THEN u.num ELSE 0 END AS vodPlayCount, CASE u.playerType WHEN 1 THEN u.flowNum ELSE 0 END AS liveFlow, CASE u.playerType WHEN 2 THEN u.flowNum ELSE 0 END AS vodFlow, 0 AS storeSpace
                , 0 AS storeResidueSpace
            FROM (
                SELECT playerType, COUNT(*) AS num, ifnull(SUM(bytesSend),0) AS flowNum
                FROM tbl_player_statistics
                WHERE playerTime BETWEEN CONCAT(DATE_FORMAT(#{month},%Y-%m),-01 00:00:00) AND CONCAT(DATE_FORMAT(last_day(#{month}),%Y-%m-%d), 23:59:59)
                GROUP BY playerType
            ) u
            UNION ALL
            SELECT 0 AS livePlayCount, 0 AS vodPlayCount, 0 AS liveFlow, 0 AS vodFlow, ifnull(SUM(fileSize),0) AS storeSpace
                , 8192000 - ifnull(SUM(fileSize),0) AS storeResidueSpace
            FROM tbl_person_space
        ) t
    </insert>

 

 

以上是关于insert into table (a,b,c) select的主要内容,如果未能解决你的问题,请参考以下文章

oracle 存储过程中 使用insert into Table (select) 进行数据批量添加 执行后无数据 但单独将上述insert

如何用sql语句,将表2中与表1中含有相同字符行,中的数据插入表1中

select into from 与insert into select from区别

sql insert into 插入记录后返回记录的ID

oracle SELECT INTO 和 INSERT INTO SELECT 两种表复制语句详解

INSERT INTO .. ON DUPLICATE KEY UPDATE 为多个项目