Where 子句检查另一个 table 中的两列
Where clause to check against two columns in another table
出于某种原因,我很难得到这个答案。
我有两个表,table1 和 table2,如下所示:
表 1:
ID Location Warehouse
1 London Narnia
2 Cyprus Metro
3 Norway Neck
4 Paris Triumph
表 2:
ID Area Code
1 London Narnia
2 Cyprus Metro
3 Norway Triumph
4 Paris Neck
我需要首先 select table1 中的所有内容,其中 table1.Location
在 table2.Area
AND table1.Warehouse
在 table2.Code
假设 table1.Location
在 table2.Area
中。 IE。我要:
ID Location Warehouse
1 London Narnia
2 Cyprus Metro
我必须:
select
1.location
, 1.warehouse
from table1 1
where 1.location in (select area from table2)
and 1.warehouse in (select code from table2)
但这行不通,因为我需要根据第一个 where 子句成立来执行第二个 where 子句。
我也尝试过类似的查询与连接无济于事。
有没有简单的方法来做到这一点?
使用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
);
我应该指出一些数据库支持带有 in
的行构造函数。这使您可以:
select t.location, t.warehouse
from table1 t
where(t1.location, t1.warehouse) in (select t2.area, t2.code from table2 t2);
您需要使用 JOIN
。
我稍后会设计查询:)
编辑:
SELECT
1.location
, 1.warehouse
FROM table1 1
JOIN table2 2 ON 1.location = 2.area AND 1.warehouse = 2.code
也许我遗漏了一些东西,但是对这两个条件的简单连接会给你示例中的结果:
select t1.*
from table1 t1
join table2 t2 on t1.Location = t2.Area
and t1.Warehouse = t2.Code;
结果:
| ID | Location | Warehouse |
|----|----------|-----------|
| 1 | London | Narnia |
| 2 | Cyprus | Metro |
出于某种原因,我很难得到这个答案。
我有两个表,table1 和 table2,如下所示:
表 1:
ID Location Warehouse
1 London Narnia
2 Cyprus Metro
3 Norway Neck
4 Paris Triumph
表 2:
ID Area Code
1 London Narnia
2 Cyprus Metro
3 Norway Triumph
4 Paris Neck
我需要首先 select table1 中的所有内容,其中 table1.Location
在 table2.Area
AND table1.Warehouse
在 table2.Code
假设 table1.Location
在 table2.Area
中。 IE。我要:
ID Location Warehouse
1 London Narnia
2 Cyprus Metro
我必须:
select
1.location
, 1.warehouse
from table1 1
where 1.location in (select area from table2)
and 1.warehouse in (select code from table2)
但这行不通,因为我需要根据第一个 where 子句成立来执行第二个 where 子句。
我也尝试过类似的查询与连接无济于事。
有没有简单的方法来做到这一点?
使用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
);
我应该指出一些数据库支持带有 in
的行构造函数。这使您可以:
select t.location, t.warehouse
from table1 t
where(t1.location, t1.warehouse) in (select t2.area, t2.code from table2 t2);
您需要使用 JOIN
。
我稍后会设计查询:)
编辑:
SELECT
1.location
, 1.warehouse
FROM table1 1
JOIN table2 2 ON 1.location = 2.area AND 1.warehouse = 2.code
也许我遗漏了一些东西,但是对这两个条件的简单连接会给你示例中的结果:
select t1.*
from table1 t1
join table2 t2 on t1.Location = t2.Area
and t1.Warehouse = t2.Code;
结果:
| ID | Location | Warehouse |
|----|----------|-----------|
| 1 | London | Narnia |
| 2 | Cyprus | Metro |