简体   繁体   中英

MySQL Inserting Multiple Columns and Rows into a Temporary Table

I have a temporary table:

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)
);

I then try to add on new values into this table

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)
);

And this line throws error. Error given:

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use

near 'SELECT COUNT(*) as count, year(end_date) FROM b
WHERE column_1 = "some condition" ' at line 3

What I'm trying to achieve is for the new rows and columns which were selected to be inserted into the temporary table. Any ideas?

After the first query, temp table should look like this:

count  year
3      2012
20     2013
104    2011

And the selected results from the second query looks like this

count  year
6      2013

The expected outcome:

count  year
3      2012
20     2013
104    2011
6      2013

Try without the "VALUES" in your Insert statement Syntax: 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM