2

我有以下表格:

父亲

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 新手

4

2 回答 2

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
于 2012-04-18T08:54:45.803 回答
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
于 2012-04-18T08:57:47.683 回答