使用相同的子选择上的Union

huangapple go评论70阅读模式
英文:

Using Union on the same subselect

问题

SELECT "a" as var1, foo FROM (SELECT foo FROM table1) as a 
UNION 
SELECT "b" as var1, foo FROM a
我能将这个UNION改成只执行一次子查询吗

我问这个是因为目前这看起来很愚蠢,对于大表table1或更复杂的子查询(这只是一个最小的例子),有可能提升计算时间。

我尝试过这个,看起来像是我想要的,但不起作用:

SELECT "a" as var1, per FROM (SELECT per FROM selectpers) as a 
UNION 
SELECT "b" as var1, per FROM a
英文:
SELECT "a" as var1, foo FROM (SELECT foo FROM table1) as a 
UNION`  
SELECT "b" as var1, foo FROM (SELECT foo FROM table1) as b

Can I change this UNION to only do the sub select once?

I am asking because currently this looks stupid and for large table1 or more complex sub selects (this is just a minimal example) there is potential for make the computation time better.

I tried this, which would look like what i want but doesn't work:

SELECT "a" as var1, per FROM (SELECT per FROM selectpers) as a
UNION SELECT "b" as var1, per FROM a

答案1

得分: 0

SELECT x.var1, table1.foo
FROM table1
CROSS JOIN ( SELECT 'a' as var1
             UNION ALL
             SELECT 'b'
             ) x
英文:
SELECT x.var1, table1.foo
FROM table1
CROSS JOIN ( SELECT 'a' as var1
             UNION ALL
             SELECT 'b'
             ) x

</details>



huangapple
  • 本文由 发表于 2023年7月3日 18:00:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76603692.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定