Having issues creating a temporary table out of a UNION

我怕爱的太早我们不能终老 提交于 2020-01-14 09:58:26

问题


I have a UNION statement that executes just fine by itself:

SELECT "1999999999" AS MobileNo, "Test" AS FirstName, "Last" AS LastName, "268" AS TemplateID, "" AS MISC1, "" AS MISC2 UNION SELECT cust.cellp AS MobileNo, acct.firstname AS FirstName, acct.lastname AS LastName, "268" AS TemplateID, "" AS MISC1, "" AS MISC2 FROM acct INNER JOIN cust ON (cust.socsec=acct.socsec)

However when I try to wrap it with a CREATE TEMPORARY TABLE:

CREATE TEMPORARY TABLE temptable (SELECT "1999999999" AS MobileNo, "Test" AS FirstName, "Last" AS LastName, "268" AS TemplateID, "" AS MISC1, "" AS MISC2 UNION SELECT cust.cellp AS MobileNo, acct.firstname AS FirstName, acct.lastname AS LastName, "268" AS TemplateID, "" AS MISC1, "" AS MISC2 FROM acct INNER JOIN cust ON (cust.socsec=acct.socsec))

I get this error:

ERROR 1064 (42000): 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 'UNION SELECT cust.cellp AS MobileNo, acct.firstname AS FirstName, ac' at line 1

Either SELECT statement works fine with the CREATE TEMPORARY TABLE around it, it is just the UNION that doesn't work. The MySQL error returned is vague so I can't quite figure out what the issue is. I tried wrapping each SELECT statement in parenthesis but it didn't like that either.

I know that in theory I could just create the temporary table using one SELECT and then add the data from the second one to the table, but that solution is not really feasible in this case as it is a report generator I am using that is pretty strict about only allowing a single MySQL statement as input so unless I wanted to redesign the whole system (I don't, nor would management want me to spend time on that right now) I have to find a way to make this work in a single MySQL statement.

Any ideas on what I'm doing wrong here?


回答1:


Here' a workaround:

CREATE TABLE AS
   SELECT *
   FROM (
       SELECT ...
       UNION ALL
       SELECT ...
   ) AS foo

You can't do the union directly for the create table, but you can make it a sub-select:

mysql> create table foo as (select * from ((select 'foo') union all (select 'bar')) as foo);
Query OK, 2 rows affected (0.00 sec)
Records: 2  Duplicates: 0  Warnings: 0


来源:https://stackoverflow.com/questions/31751682/having-issues-creating-a-temporary-table-out-of-a-union

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!