SQL - 返回至少有一个值为 'Y' 的所有行

标签 sql distinct

我的问题与上一篇文章非常相似 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 子句中的派生表,具体取决于实际架构以及 table1table2代表。

关于SQL - 返回至少有一个值为 'Y' 的所有行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30520964/

相关文章:

mysql - 在大 View 上优化 MySQL GROUP BY 或 DISTINCT

mysql - 将 2 个表连接在一起并使用基于单独 mysql 查询的 where 函数

sql - 获取事务中插入的记录数

sql - 错误 : ORA-00955: name is already used by an existing object in Oracle Function

sql - 如何更新记录的所有列而不必列出每一列

mysql - Right Join 不返回右侧表中的所有记录

sql - Oracle SQL : Return a string based on which column has the highest value

sql - 使用 R 对两列进行分组并计算不同值

c# - 在 C# 中实现 Linq Distinct

mysql不同的行或不同的字段