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>