查找表,使用查找中的AND来获取一个结果

时间:2015-01-04 18:10:12

标签: sql nhibernate fluent-nhibernate

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

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

表2与表1和表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中获取1个结果,查找表3中的代码。

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

1 个答案:

答案 0 :(得分:1)

这是一个基本的集内问题。我想使用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;