Lookup Table,在Lookup中使用AND取回一个结果

Lookup Table, using AND in Lookup to get one result back

我在谷歌上搜索了一个小时左右,只能找到 2 table 个答案。

Table1 - (ID uniqueidentifier PK)
Table2 - (ID uniqueidentifier PK, uniqueidentifier Table1ID, uniqueidentifier Table3ID)
Table3 - (ID uniqueidentifier PK, varchar(5) Code)

Table2 与 Table1 和 Table 3

具有多对一关系

所以示例数据类似于

Table1 (1)
Table2 (1, 1, 1)
Table2 (2, 1, 2)
Table2 (3, 1, 3)
Table3 (1, 'ABC')
Table3 (2, "DEF')
Table3 (3, "GHI')

我只想从 Table1 查找 Table3 上的代码返回 1 个结果。

Example1: If I searched 'ABC' AND 'GHI', I would only get 1 result back
Example2: 'DEF' and "JKL' would not return a result since 'JKL' isn't linked in Table2

这是一道基本的套中题。我喜欢使用 group byhaving 来解决这些问题,因为这是最灵活的解决方案。据我所知,实际上不需要 table1

select t2.Table1Id
from table2 t2 join
     table3 t3
     on t2.Table3ID = t3.Id
group by t2.table1Id
having sum(case when t3.code = 'ABC' then 1 else 0 end) > 0 and
       sum(case when t3.code = 'GHI' then 1 else 0 end) > 0;

我喜欢这个解决方案的原因是它非常灵活。如果你想要 ABC 而不是 GHI,你可以使用:

having sum(case when t3.code = 'ABC' then 1 else 0 end) > 0 and
       sum(case when t3.code = 'GHI' then 1 else 0 end) = 0;

如果您想要 XYZ 以及其他两个:

having sum(case when t3.code = 'ABC' then 1 else 0 end) > 0 and
       sum(case when t3.code = 'GHI' then 1 else 0 end) > 0 and
       sum(case when t3.code = 'XYZ' then 1 else 0 end) > 0;