我的问题与上一篇文章非常相似 SQL Query, get a columns if another columns equal to x
唯一的区别是我正在连接两个表,而之前的解决方案似乎不起作用。基本上,一旦表被连接,我就有两列。我想要一个名称的所有行,其中该名称的至少一行具有“Shasta”作为位置。例如,
第 1 列 = 名称(来自表 1) 第 2 列 = 位置(来自表 2)
Name | Location
-------------------
Bob | Shasta
Bob | Leaves
Sean | Leaves
Dylan | Shasta
Dylan | Redwood
Dylan | Leaves
应该返回:
Name | Location
--------------------
Bob | Shasta
Bob | Leaves
Dylan | Shasta
Dylan | Redwood
Dylan | Leaves
我尝试了上一篇文章的解决方案
where x in
(
select distinct x
from table 1
where y like 'Shasta'
)
不幸的是,它只返回:
Name | Location
--------------------
Bob | Shasta
Dylan | Shasta
最佳答案
您正在寻找 WHERE EXISTS
子句。作为说明,我们假设您有以下查询:
select a.Name, b.Location
from table1 a
join table2 b on a.TableBId = b.Id
您希望检索此查询中的所有行,其中同一查询结果中存在具有该名称
的行,并且位置='沙斯塔'
。因此,我们可以将查询用作派生表,匹配 Name
并查找 Location = 'Shasta'
:
select a.Name, b.Location
from table1 a
join table2 b on a.TableBId = b.Id
where exists (
select 1
from
(
select a.Name, b.Location
from table1 a
join table2 b on a.TableBId = b.Id
) x --this is the same as the above query, as a derived table
where x.Name = a.Name --correlate the queries by matching the Name
and x.Location = 'Shasta' --look for the column value in question
)
当然,您可以简化此查询和/或消除 WHERE EXISTS
子句中的派生表,具体取决于实际架构以及 table1
和 table2
代表。
关于SQL - 返回至少有一个值为 'Y' 的所有行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30520964/