MySQL将多列和行插入临时表

时间:2013-08-21 03:35:24

标签: mysql

我有一张临时表:

CREATE TEMPORARY TABLE IF NOT EXISTS `temp`
AS (
 SELECT COUNT(*) as count, YEAR(end_date)
 FROM a
 WHERE column_1 = "some_condition"
 GROUP BY YEAR(end_date)
);

然后我尝试在此表中添加新值

INSERT INTO temp (count, year)
VALUES(
  SELECT COUNT(*) as count, year(end_date)
  FROM b
  WHERE column_1 = "some_condition"
  GROUP BY YEAR(end_date)
);

此行抛出错误。 给出错误:

  

1064 - 您的SQL语法出错;检查与MySQL服务器版本对应的手册,以获得正确的语法

     

在'SELECT COUNT(*)附近作为计数,年(end_date)FROM b
  WHERE column_1 =第3行的“某些条件”

我想要实现的是选择要插入临时表的新行和列。有什么想法吗?

第一次查询后,临时表应如下所示:

count  year
3      2012
20     2013
104    2011

第二个查询的选定结果如下所示

count  year
6      2013

预期结果:

count  year
3      2012
20     2013
104    2011
6      2013

1 个答案:

答案 0 :(得分:3)

在Insert语句中尝试不使用“VALUES” 语法:http://www.w3schools.com/sql/sql_insert_into_select.asp

INSERT INTO `temp` (`count`, `year`)
  SELECT
    COUNT(*),
    year(`end_date`)
  FROM `b`
  WHERE `column_`` = "condition" GROUP BY YEAR(end_date);