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>

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值