基于多行的WHERE子句进行选择

时间:2014-04-29 18:33:14

标签: sql sqlite

我有一个像这样的SQLite表:

GroupID UserID
1       1
1       2
1       3
2       4
2       1

......等等。然后,给定一个UserID列表,我想得到一个groupID,它包含所有那些userID,只有那些userID。

例如,在此表中,给定一个列表(1,2,3),返回的值应为1.对于列表(1,4),它应为2.对于列表(1,2)或(3,4),不应归还任何东西。

最好的方法是什么?

3 个答案:

答案 0 :(得分:0)

select GroupID 
from your_table 
where UserID in (1,2,3)
GROUP BY GroupID
HAVING COUNT(*) = 3

答案 1 :(得分:0)

你在这个问题上有点不清楚。会" 1"如果列表是2和3,则返回?

这是set-within-sets子查询的示例。最通用和最灵活的方法是使用带有having子句的聚合:

select GroupId
from table t
group by GroupId
having sum(case when UserId = 1 then 1 else 0 end) > 0 and
       sum(case when UserId = 2 then 1 else 0 end) > 0 and
       sum(case when UserId = 3 then 1 else 0 end) > 0 and
       sum(case when UserId not in (1, 2, 3) then 1 else 0 end) = 0;

每个子句计算每个用户出现的次数。 > 0要求每个用户至少出现一次。

您可能会发现将其表达为:

select GroupId
from table t
group by GroupId
having count(distinct case when UserId in (1, 2, 3) then UserId) = 3 and
       count(distinct UserId) = count(*);

但是,你必须确保" 3"匹配in语句中的元素数。

答案 2 :(得分:0)

您还可以使用从属子查询:

SELECT * 
FROM myTable t1
WHERE UserID IN (1, 2, 3) 
  AND NOT EXISTS 
      (SELECT 1 
       FROM myTable t2 
       WHERE t2.GroupId = t1.GroupId 
         AND UserId NOT IN (1, 2, 3));

用简单的英语,您选择包含指定UserId值的记录,并拒绝任何不包含所有三个值的记录。这种方法的优点是允许在IN子句中允许任意数量的元素,而无需准确知道您传入的数量。

相关问题