内连接表2或表3

时间:2017-09-07 09:25:07

标签: sql select join

我有三个表table1,table2,table3

table1和table2是具有几乎相同结构的主表

table3与两个表链接,一半记录取决于table1,一半取决于table2

我想要这样的东西

select a.column1,a.column2, c.column1
from table3 c
     inner join table1 a ON a.pkey = c.fkey
  OR inner join table2 a ON a.pkey = c.fkey

2 个答案:

答案 0 :(得分:1)

您可以使用union all来模拟此行为:

SELECT a.column1, a.column2, c.column1
FROM  table3 c
INNER JOIN (SELECT column1, fkey
            FROM   table1
            UNION ALL
            SELECT column1, fkey
            FROM   table2) a ON a.pkey = c.fkey

答案 1 :(得分:1)

如果您关心效果,我建议您使用left join

select coalesce(t1.column1, t2.column1) as column1,
       coalesce(t1.column2, t2.column2) as column2,
       c.column1
from table3 c left join
     table1 t1
     on t1.pkey = c.fkey left join
     table2 t2
     on t2.pkey = c.fkey
where t1.pkey is not null or t2.pkey is not null;

这可以利用table1(pkey, column1, column2)table2(pkey, column1, column2)上的索引。