SQL - 获取"确切"父亲与孩子们比赛

时间:2012-04-18 08:49:00

标签: sql

我有以下表格:

ID
------
a
b
c

f_ID    ID
------------
a        1
a        2
a        3
b        1
b        2
c        1

我想:

  • 当我[1,2,3]
  • 时获得“a”
  • 当我[1,2]
  • 时获得“b”
  • 当我[1]
  • 时获取“c”

问题是如果我使用

SELECT *    
FROM Father AS F    
INNER JOIN Child AS C    
ON C.f_ID = F.ID    
WHERE C.ID IN ( '1' )    

这将给我父亲:1,2,3

请帮忙,我是SQL的新手

2 个答案:

答案 0 :(得分:1)

试试这样。我只是添加了一个"并且不存在"在你的Where子句的末尾。

SELECT * Father AS F
INNER JOIN Child AS C
    ON C.f_ID = F.ID
WHERE C.ID IN ( '1' )
AND NOT EXISTS (
    SELECT * FROM Child
    WHERE Child.ID NOT IN ('1')
    AND F.ID = Child.f_ID
)

作为替代方法,您可以自行连接并选择空行。

SELECT * Father AS F
INNER JOIN Child AS C
    ON C.f_ID = F.ID AND C.ID IN ( '1' )
LEFT OUTER JOIN
    (SELECT f_ID FROM Child WHERE ID NOT IN ('1')) a
    ON C.f_ID = a.f_ID
WHERE a.f_ID IS NULL

答案 1 :(得分:0)

为了能够匹配整个序列,您需要计算匹配并将其与给定序列的计数进行比较:

select f.f_id
  from father f
 inner join child c
    on f.f_id = c.f_id
 -- exact sequence given
 where c.f_id in (1, 2, 3)
group by f_id
-- compare number of children to number of elements in parameter sequence
having count (distinct c.c_id) = 3