SELECT

时间:2018-03-07 10:18:51

标签: mysql join subquery union lateral-join

说我的查询看起来像这样:

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

这很好用。现在,假设我想将这些结果与ab相反,即:

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都可以引用它?

0 个答案:

没有答案