SQL:将查询结果插入到另一个表的三种情况
一:如果要插入目标表不存在:
select * into 目标表 from 表 where ...
二:如果要插入目标表已经存在:
insert into 目的表 select * from 表 where 条件
三:如果是跨数据库操作的话: 怎么把A数据库的atable表所查询的东西,全部插入到B 数据库的btable表中
select * into B.btable from A.atable where ...
同样,如果是跨服务器的,也是可以的。
select count( case when rule_name='RULE_1' then shop_id end) as risk_rule_1 , count( case when rule_name='RULE_2' then rule_name end) as risk_rule_2 , count( case when rule_name='RULE_3' then rule_name end) as risk_rule_3 , count( case when rule_name='RULE_4' then rule_name end) as risk_rule_4 , count( case when rule_name='RULE_5' then rule_name end) as risk_rule_5 from select_table where date(check_time)=20170828; +-------------+-------------+-------------+-------------+-------------+ | risk_rule_1 | risk_rule_2 | risk_rule_3 | risk_rule_4 | risk_rule_5 | +-------------+-------------+-------------+-------------+-------------+ | 0 | 18 | 0 | 1 | 0 | +-------------+-------------+-------------+-------------+-------------+ insert into insert_table (risk_rule_1,risk_rule_2,risk_rule_3,risk_rule_4,risk_rule_5) select count( case when rule_name='RULE_1' then shop_id end) as risk_rule_1 , count( case when rule_name='RULE_2' then rule_name end) as risk_rule_2 , count( case when rule_name='RULE_3' then rule_name end) as risk_rule_3 , count( case when rule_name='RULE_4' then rule_name end) as risk_rule_4 , count( case when rule_name='RULE_5' then rule_name end) as risk_rule_5 from select_table where date(check_time)=20170828;
mysql> select * from risk_cash_rules_number\G; *************************** 1. row *************************** id: 1 trusted_rule_1: 0 trusted_rule_2: 0 trusted_rule_3: 0 risk_rule_1: 0 risk_rule_2: 18 risk_rule_3: 0 risk_rule_4: 1 risk_rule_5: 0 date: 19710101 1 row in set (0.00 sec)