简体   繁体   English

如何在SQL中使用或条件连接3个表

[英]How to join 3 tables in sql with or condition

I have 3 tables: table1 我有3张桌子:table1

  • inner join with table2; 与table2内部连接; or: 要么:
  • inner join with table3 与table3内部联接

The query: 查询:

select table1.x
from table1 right outer join
     table2
     on table1.x = table2.x right outer join
     table3
     on table1.x = table3.x

but I can only see x values that are in both table2 and table3 但我只能看到table2和table3中的x值

Use left join , not right join , along with an appropriate filter condition: 使用left join而不是right join以及适当的过滤条件:

select table1.x
from table1 left join
     table2
     on table1.x = table2.x left join
     table3
     on table1.x = table3.x
where table2.x is not null or table3.x is not null;

You might consider writing this using exists : 您可以考虑使用exists编写此代码:

select t1.*
from table1 t1
where exists (select 1 from table2 t2 where t2.x = t1.x) or
      exists (select 1 from table3 t3 where t3.x = t1.x);

That seems like a more natural way to implement your logic -- and you won't get duplicates when x is duplicated in table2 or table3 . 这似乎是实现逻辑的一种更自然的方法-当xtable2table3重复时,您将不会重复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM