我有一个UNION语句,它自己执行得很好:
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)
然而,当我尝试用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))
我收到此错误:
错误1064(42000):您的SQL语法有错误;查看与MySQL服务器版本对应的手册,以便在'UNION SELECT cust.cellp AS MobileNo附近使用正确的语法,acct.firstname AS FirstName,ac'在第1行
SELECT语句可以正常使用它周围的CREATE TEMPORARY TABLE,它只是不起作用的UNION。返回的MySQL错误很模糊,所以我无法弄清问题是什么。我尝试在括号中包装每个SELECT语句,但它也不喜欢。
我知道理论上我可以使用一个SELECT创建临时表,然后将第二个数据添加到表中,但在这种情况下该解决方案实际上并不可行,因为它是我正在使用的报表生成器这是非常严格的只允许一个MySQL语句作为输入,所以除非我想重新设计整个系统(我没有,管理层也不希望我现在花时间),我必须找到一种方法来做到这一点在一个MySQL语句中工作。
关于我在这里做错了什么想法?
答案 0 :(得分:5)
下面'解决方法:
CREATE TABLE AS
SELECT *
FROM (
SELECT ...
UNION ALL
SELECT ...
) AS foo
您无法直接为create table
执行联合,但您可以将其作为子选择:
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