1

我有一个临时表:

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(*) as count, year(end_date) FROM b
WHERE column_1 = "some condition"' 在第 3 行附近

我想要实现的是选择要插入到临时表中的新行和列。有任何想法吗?

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

count  year
3      2012
20     2013
104    2011

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

count  year
6      2013

预期结果:

count  year
3      2012
20     2013
104    2011
6      2013
4

1 回答 1

3

尝试在插入语句中不使用“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);
于 2013-08-21T03:39:37.343 回答