我正在使用以下查询来仅显示具有这两种资格的检查员。
DECLARE @CertType QualificationType; --2,3
select i.InspectorID from Inspectors i
INNER JOIN (
SELECT _id.InspectorID
FROM InspectorDocs _id
WHERE _id.QualificationTypeID IN (select [QualificationTypeID] from @CertType) GROUP BY _id.InspectorID
HAVING COUNT(DISTINCT _id.QualificationTypeID) = (select count(*) from @CertType)
) as id on id.inspectorid = i.inspectorid
有没有更好的方法来查找列是否具有所有给定的值?
模式
检查员:检查员(PK)InspectorDocs:DocID(PK),InspectorID(FK),QualificationTypeID(FK)
QualificationTypE:QualificationTypeID(PK)
答案 0 :(得分:1)
如果我没有弄错你正在做什么就是所谓的关系部门,另一种(略微不直观)表达方式的是以下查询,这应该会提供更好的性能:
select * from Inspectors i
where not exists (
select * from QualificationType c
where QualificationTypeID IN (2,3)
and not exists (
select * from InspectorDocs id
where c.QualificationTypeID = id.QualificationTypeID
and id.InspectorID = i.InspectorID))
如果您想深入研究这个主题,我建议您阅读Joe Celko的Divided We Stand: The SQL of Relational Division。