一次只在两个select语句中使用公共表

时间:2016-05-30 13:22:40

标签: sql

我有两个带有两个常见表或两个不常见表的select语句 我正在使用这两个语句的联合,但我如何使用公共表 这两个陈述只是一次

select * from (select *
from table1 t1
join table2 t2 
on t2.id = t1.id_fk
join table3 t3
on t3.id=t2.id_fk
join table4 t4
on t4.id=t3.id_fk
union
select *
from table1_arc t1
join table2_arc t2 
on t2.id = t1.id_fk
join table3 t3
on t3.id=t2.id_fk
join table4 t4
on t4.id=t3.id_fk) 
order by 1

现在看

  表3   和   表4

这两个表在两个select语句中都使用了两次。 有什么办法让我只能使用它们一次

3 个答案:

答案 0 :(得分:0)

试试这个

SELECT *
FROM (
    SELECT *
    FROM table1 t1
    JOIN table2 t2 
        ON t2.id = t1.id_fk
    union
    SELECT *
    FROM table1_arc t1
    JOIN table2_arc t2 
        ON t2.id = t1.id_fk
) A
JOIN table3 t3
    ON t3.id = A.id_fk
JOIN table4 t4
    ON t4.id = t3.id_fk
ORDER BY 1

答案 1 :(得分:0)

如果目标只是引用它们,那么它将是:

select *
from (select *
     from table1 t1
     join table2 t2 
     on t2.id = t1.id_fk
     union all
     select *
     from table1_arc t1
     join table2_arc t2 
     on t2.id = t1.id_fk) as Main
join table3 t3
on t3.id=Main.id_fk
join table4 t4
on t4.id=t3.id_fk

答案 2 :(得分:0)

试试这个,如果两个表中的ID可以具有相同的值,例如自动生成的整数,这将起作用。

select * 
  from (
     select *,
            T2.ID QueryFk1, 1 QueryKey,
        from table1 t1
        join table2 t2 
          on t2.id = t1.id_fk
  union
  select *,
            T2.ID QueryFk2, 2 QueryKey,
     from table1_arc t1
     join table2_arc t2 
       on t2.id = t1.id_fk
) A
   join table3 t3
     on (t3.id=A.QueryFk1 And A.QueryKey = 1) Or
        (t3.id=A.QueryFk2 And A.QueryKey = 2)
   join table4 t4
     on t4.id=t3.id_fk
   order by 1