SQL 选择具有特定值的不同 ID

SQL selecting distinct Ids with specific values

你能告诉我如何找到具有 FormFieldID ((1 AND 2) OR 3) 的用户吗,所以 SQL 查询应该 return UserIDs: 7, 8, 9.

table:

我使用SQL服务器。

谢谢!

我会推荐聚合和 having 子句来实现过滤 logc:

select userid
from mytable
group by userid
having 
    (
         max(case when formfieldid = 1 then 1 end) = 1 
         and max(case when formfieldid = 2 then 1 end) = 1
    )
    or max(case when formfieldid = 3 then 1 end) = 1

根据您未告知的实际数据库,可能有更简洁的选项来表达条件。例如,在 MySQL:

having 
    (max(formfieldid = 1) and max(formfieldid = 2))
    or max(formfieldid = 3)