【问题标题】:SQL Select results based on two rows with different conditionSQL 根据具有不同条件的两行选择结果
【发布时间】:2020-04-18 05:31:28
【问题描述】:

我正在尝试获取结果,我想检查是否存在两行用于一个公共 ForeignKeyId 并在这两行上添加一个检查。

假设我在下面有一个表格 - 'Test1'

A    B    C    D                               'Test2'
1    33   x    NULL                             Result       Id
2    33   NULL y                                Result1      33
3    44   x    NULL                             Result2      44
4    44   NULL z                                Result3      55
5    55   x    NULL

我想从 Test2 表中获取结果,其中 Test1 应该包含两行,其中 C = x 和 D NULL。

所以,选择查询应该返回 Result1 和 Result2,而不是 Result3

我试过了:

select Result
from Test2
inner join Test1 on Test2.Id = Test1.A
where 
    (select Count(*) from Test1 where C = 'x') = 1 AND 
    (select Count(*) from Test1 where D IS NOT NULL) = 1;

【问题讨论】:

  • 使用SQL Server
  • 下面的解决方案可能适用于 SQL Server,但结果通常取决于数据库,因此适当的标记可以节省每个人的时间。下次也应该在dba.stackexchange.com 上询问纯 SQL 和 DB 问题。

标签: sql sql-server


【解决方案1】:

为了比较不同行中的相同值,使用自连接。在这种情况下,有两个 Test1 表,第一个 (Tc) 匹配 C 条件,第二个 Td 匹配 D 条件。

SELECT Result,Tc.B
FROM Test1 Tc
JOIN Test1 Td
  ON Tc.B=Td.B
JOIN Test2
  ON Td.B=Test2.Id
WHERE
   Tc.C = 'x'
   AND Td.D IS NOT NULL

【讨论】:

    【解决方案2】:

    我建议使用exists:

    select t2.*
    from test2 t2
    where exists (select 1 from test1 t1 where t2.id = t1.b and t1.c = 'x') and
          exists (select 1 from test1 t1 where t2.id = t1.b and t1.d is not null);
    

    这样做的原因是,如果多行匹配table1 中的任一条件,您将不会得到重复。

    注意:如果table1 中的两个条件都为真,则上面可能会返回只有一个匹配行。您可以通过更精确的条件要求两行:

    where exists (select 1 from test1 t1 where t2.id = t1.b and t1.c = 'x' and t1.id is null) and
          exists (select 1 from test1 t1 where t2.id = t1.b and t1.d is not null and (t1.c <> 'x' or t1.c is null));
    

    【讨论】:

      猜你喜欢
      • 2018-11-01
      • 1970-01-01
      • 2016-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-27
      • 2014-09-22
      相关资源
      最近更新 更多