insert select忽略一些子查询返回的值

时间:2018-03-01 15:26:43

标签: mysql

我正在尝试执行插入选择,但需要一些别名值进行计算,但不需要将所有这些值用于我的插入。我只需要field0,total_sum,hard_coded_val,但依赖其他人进行计算。

有没有办法忽略其他值或在插入SELECT中指定VALUES()?

INSERT INTO table(field0,total_sum,hard_coded_val) 
  SELECT s.*, sum1+sum2 AS total_sum, 'hard_coded_val' FROM 
 (SELECT t.*, (fielda+fieldb)*2 AS sum1, (fieldc+fieldd)/4 AS sum2 from
 (SELECT field0, 
    sum(IF(field1 = 1, totalcount,0)) AS fielda,
    sum(IF(field1 = 2, totalcount,0)) AS fieldb,
    sum(IF(field1 = 3, totalcount,0)) AS fieldc,
    sum(IF(field1 = 4,totalcount,0)) AS fieldd 
  from source_table GROUP BY field0) 
    t ORDER BY sum1 DESC) 
      s ORDER BY total_sum DESC

1 个答案:

答案 0 :(得分:1)

您只需要限制返回的列数。 *将返回与其关联的表的所有列。

INSERT INTO table(field0,total_sum,hard_coded_val) 
  SELECT s.field0, sum1+sum2 AS total_sum, 'hard_coded_val' FROM
...