简体   繁体   English

如何在没有临时表的情况下对子查询的结果进行UNION?

[英]How do I UNION over the result of a subquery without a temp table?

I have a complex query which results in multiple columns which I want to UNION into a single column. 我有一个复杂的查询,该查询导致我想将多个列合并为一个列。

The naive UNION construct makes me place the FROM for each query to combine. 天真的UNION构造使我可以将FROM从每个查询中组合起来。 I would like that FROM to be the result of the complex query. 我希望FROM是复杂查询的结果。

I would like to say: 我想说:

SELECT row1 AS result FROM (complex query)
UNION
SELECT row2 AS result FROM (same complex query)
UNION
SELECT row3 AS result FROM (same complex query)
...

How do I do that in MySQL 5.6.10 (I realize that CTE elegantly solves my problem), and without temp tables (my DBA is paranoid). 如何在MySQL 5.6.10(我意识到CTE很好地解决了我的问题)中做到了这一点,并且没有临时表(我的DBA偏执狂)。

You can use a cte block like below: 您可以使用如下所示的cte块:

with cte as
(
   complex query comes here
)
select row1 as result from cte
union
select row2 as result from cte
...

Using a temptable would be another alternative solution. 使用模板是另一种替代解决方案。

For more cte examples: http://www.mysqltutorial.org/mysql-cte/ 有关更多的cte示例: http : cte

EDIT: Since OP is using an older version, this is an alternative solution: 编辑:由于OP使用的是较旧的版本,这是一个替代解决方案:

Use a #temp table like below in your main complex query: 在主要的复杂查询中使用如下所示的#temp表:

Select ...
into #temp
from ...
...

Then, use the #temp table for union: 然后,使用#temp表进行联合:

select row1 as result from #temp
union
select row2 as result from #temp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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