我有一个tableX作为:
|-column1-|-column2-|
| a1 | b4 |
| a2 | b5 |
| a3 | b6 |
我想将这些值选择为一列作为结果:
|-result--|
| a1 |
| a2 |
| a3 |
| b4 |
| b5 |
| b6 |
看起来很简单,但是所有我认为它们只是将值合并/合并到单个列中的问题。我需要将它们添加为“列表”。
我可以使用union子句,例如:
select column1 as result from tableX
UNION
select column2 as result from tableX
但是性能会很差(慢2倍),而且我的SQL语句会很庞大,因为tableX是一个非常复杂的子查询(不利于维护和可读性)。
标记为MySQL,但我将接受所有DBMS的答案
首先,我建议union all
而不是union
,所以:
select column1 as result from tableX
union all
select column2 as result from tableX;
union
删除重复项会产生开销。如果tableX
是一张桌子,那可能很好。尽管对表进行了两次扫描,但是在大多数情况下,表页面已经在页面缓存中,因此第二次扫描应该比第一次扫描快得多。
如果tableX
确实是一个复杂的视图,则可以执行一些更有效的操作:
select (case when n.n = 1 then column1 else column2 end) as column
from tableX cross join
(select 1 as n union all select 2) n;
如果您仍然需要删除重复项,请使用select distinct
:
select distinct (case when n.n = 1 then column1 else column2 end) as column
from tableX cross join
(select 1 as n union all select 2) n;
但是,这可能会抵消任何性能提升。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句