我正在尝试运行查询但无法获取
这是结构:
Person:
IdPerson
FirstName
LastName
...
CustomField
IdField
....
CustomFieldXPerson
IdField
IdPerson
Value
Filter:
IdField
Value
Criteria (<, >, <=, >=, =)
GroupId
我需要让所有与所有过滤器匹配的人,并让所有匹配至少一个人...
SELECT IdPerson
FROM Person p
JOIN CustomFieldXPerson cfxp on cfxp.IdPerson = p.IdPerson
JOIN Filter f on f.IdField = cfxp.IdField AND f.Value (f.Criteria) cfxp.Value
WHERE f.GroupId = X
有一种简单的方法可以动态地执行此操作吗?
答案 0 :(得分:2)
您可以将您的查询表达为:
SELECT IdPerson
FROM Person p JOIN
CustomFieldXPerson cfxp
on cfxp.IdPerson = p.IdPerson JOIN
Filter f
on f.IdField = cfxp.IdField AND
(f.Criteria = '=' and f.Value = cfxp.Value or
f.Criteria = '<' and f.Value < cfxp.Value or
f.Criteria = '<=' and f.Value <= cfxp.Value or
f.Criteria = '>' and f.Value > cfxp.Value or
f.Criteria = '>=' and f.Value >= cfxp.Value
)
WHERE f.GroupId = X ;
编辑:
如果您想获得符合所有过滤条件的人,请使用group by
:
SELECT IdPerson
FROM Person p JOIN
CustomFieldXPerson cfxp
on cfxp.IdPerson = p.IdPerson LEFT JOIN
Filter f
on f.IdField = cfxp.IdField AND
(f.Criteria = '=' and f.Value = cfxp.Value or
f.Criteria = '<' and f.Value < cfxp.Value or
f.Criteria = '<=' and f.Value <= cfxp.Value or
f.Criteria = '>' and f.Value > cfxp.Value or
f.Criteria = '>=' and f.Value >= cfxp.Value
) AND
f.GroupId = X
GROUP BY idPerson
HAVING COUNT(f.IdField) = COUNT(*) OR COUNT(f.IdField) = 0;
换句话说,与群组中的人匹配的所有过滤器都匹配。 HAVING
子句中的附加条件是过滤器组没有过滤器。