如何从树和结构之间存在一对一关系的表中选择不同的树?

时间:2015-07-30 11:55:48

标签: sql

我有一个名为Checks的表格,如下所示:

treeId   checkId
 1       2
 1       4
 2       4
 2       5

我想选择不同的树在哪里 checkId在[1,2,3]中 checkId在[4,5]

所以结果应该只返回1

我有什么:

Select * FROM Checks
WHERE checkId IN (1, 2, 3)
AND checkId IN (4, 5)

但是没有结果

更新

  1. 获取[1,2,3]中的treeIds,返回输出集
  2. 从输出集中选择[4,5]中的树创建outputset2
  3. 只应返回1

    附加

    如果有更多条件,请说:

    1. 从outputset2中选择[6,7]
    2. 中的树

2 个答案:

答案 0 :(得分:0)

这将为您treeid提供至少1 checkID的4,5和至少1 checkID的1,2,3:

SELECT DISTINCT c1.treeid
FROM Checks c1
where (select count(c2.checkid) from Checks c2 where c2.checkID in (4,5) and c2.treeid=c1.treeid) > 0
and (select count(c2.checkid) from Checks c2 where c2.checkID in (1,2,3) and c2.treeid=c1.treeid) > 0

答案 1 :(得分:0)

这应该满足您的需求see sqlfiddle

SELECT DISTINCT
    treeId
FROM Checks c1
WHERE 
(SELECT COUNT(*) FROM Checks c2 WHERE c1.treeId = c2.treeId AND c2.checkId IN (1,2,3))
AND (SELECT COUNT(*) FROM Checks c2 WHERE c1.treeId = c2.treeId AND c2.checkId IN (4,5))
AND (SELECT COUNT(*) FROM Checks c2 WHERE c1.treeId = c2.treeId AND c2.checkId IN (6,7));

要添加其他条件,如果a,b,c,d,e是您的新条件,只需添加新条件

AND (SELECT COUNT(*) FROM Checks c2 WHERE c1.treeId = c2.treeId AND c2.checkId IN (a,b,c,d,e));