假设我有一个看起来像这样的查询:
select step0.a, step1.a, step2.a
from (select id from tbl1) as step
inner join tbl1 as step0 on step0.id = step.id
left join tbl1 as step1 on step1.b = step0.a
left join tbl1 as step2 on step2.b = step1.a
这工作正常。现在,假设我想将这些结果与 and 的反向联合a
,b
即:
select * from (
(
select step0.a, step1.a, step2.a
from (select id from tbl1) as step
inner join tbl1 as step0 on step0.id = step.id
left join tbl1 as step1 on step1.b = step0.a
left join tbl1 as step2 on step2.b = step1.a
)
union (
select step0.b, step1.b, step2.b
from (select id from tbl1) as step
inner join tbl1 as step0 on step0.id = step.id
left join tbl1 as step1 on step1.a = step0.b
left join tbl1 as step2 on step2.a = step1.b
)
) rows
这也很好用。但请注意,select id from tbl1
子查询是重复的。
我的问题是,如何在不使用临时表的情况下存储此子查询的结果,以便select
联合中的每个都可以引用它?