Where 子句检查另一个表中的两列

Joh*_*han 2 sql join where-clause where-in

由于某种原因,我正在努力获得这个答案。

我有两个表,table1 和 table2,它们看起来像这样:

表格1:

ID   Location  Warehouse
1    London    Narnia
2    Cyprus    Metro
3    Norway    Neck
4    Paris     Triumph
Run Code Online (Sandbox Code Playgroud)

表2:

ID   Area      Code
1    London    Narnia
2    Cyprus    Metro
3    Norway    Triumph
4    Paris     Neck
Run Code Online (Sandbox Code Playgroud)

我需要首先从 table1 中选择所有内容,其中table1.Location位于table2.Area AND table1.Warehousetable2.Code GIVEN THAT table1.Location is in table2.Area. 即我想要:

ID   Location  Warehouse
1    London    Narnia
2    Cyprus    Metro
Run Code Online (Sandbox Code Playgroud)

我必须:

select
  1.location
, 1.warehouse
from table1 1
where 1.location in (select area from table2)
and 1.warehouse in (select code from table2)
Run Code Online (Sandbox Code Playgroud)

但这行不通,因为我需要根据第一个 where 子句成立来执行第二个 where 子句。

我也尝试过类似的连接查询,但无济于事。

有没有一种简单的方法可以做到这一点?

Gor*_*off 7

使用exists

select t.location, t.warehouse
from table1 t
where exists (select 1
              from table2 t2
              where t.location = t2.area and t.warehouse = t2.code
             );
Run Code Online (Sandbox Code Playgroud)

我应该指出一些数据库支持带有in. 这允许您执行以下操作:

select t.location, t.warehouse
from table1 t
where(t1.location, t1.warehouse) in (select t2.area, t2.code from table2 t2);
Run Code Online (Sandbox Code Playgroud)