[英]How to join 3 tables in sql with or condition
I have 3 tables: table1 我有3张桌子:table1
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
. 这似乎是实现逻辑的一种更自然的方法-当x
在table2
或table3
重复时,您将不会重复。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.