SQL筛选器记录在ID列表上

时间:2016-12-11 13:58:47

标签: sql

我有以下联结表:

PersonPhoto

+----+----------+---------+
| Id | PersonId | PhotoId | 
+----+----------+---------+
|  1 |       10 |       5 |
|  2 |       11 |       8 |
|  3 |       12 |      28 |
|  4 |       10 |      15 |
|  5 |       10 |      28 |
|  6 |       12 |      15 |
+----+----------+---------+

我正在尝试过滤表格,只根据PersonId的列表返回PhotoId

例如

我想获得所有与其关联的用户10和12的Photo ID。使用上面的表格应该返回以下照片ID

15和28 ..

目前我的努力是返回15,28,5 - 但我不想要5被退回,因为Person Id 12与照片ID 5无关

这是我已经尝试过的事情:

select distinct pe.PhotoId 
from PersonPhoto AS pe
where pe.PersonId IN (10, 12)
GROUP BY pe.PhotoId

select pp.PersonId, pp.PhotoId from PersonPhoto AS pp
where pp.PersonId IN (10, 12)
GROUP BY pp.PersonId, pp.PhotoId
HAVING COUNT(DISTINCT pp.PhotoId) = 1

有什么想法吗?

3 个答案:

答案 0 :(得分:2)

假设您想要获得包含所有所需人物的照片,那么一种方法是使用group byhaving

select pp.PhotoId
from PersonPhoto pp
where pp.PersonId in (10, 12)
group by pp.PhotoId
having count(*) = 2;

如果您可以在表格中包含重复项,那么您应该在count(distinct PersonId)子句中使用having

答案 1 :(得分:1)

您可以使用下面的INTERSECT运算符。虽然它不适用于MySQL(您有SQL Server标记的)

(SELECT DISTINCT PhotoId  FROM PersonPhoto WHERE PersonId = 10)
INTERSECT
(SELECT DISTINCT PhotoId  FROM PersonPhoto WHERE PersonId = 12)

对于MySQL,这会起作用。取自Mysql intersect results

的想法
SELECT DISTINCT PhotoId FROM PersonPhoto
INNER JOIN (SELECT DISTINCT PhotoId  FROM PersonPhoto WHERE PersonId = 10) a USING (PersonId)
INNER JOIN (SELECT DISTINCT PhotoId  FROM PersonPhoto WHERE PersonId = 12) b USING (PersonId)

答案 2 :(得分:0)

或使用exists编写查询。然后它完全按你所说的那样读。

Select distinct photoId    -- get all Photo Ids that     
From @myT a
Where exists (Select * from @myT  -- have the users 10 
              Where photoId = a.photoId
                 and personId = 10)
  and exists (Select * from @myT  -- and 12 associated with them
              Where photoId = a.photoId
                 and personId = 12)