如何在同一表格中进行查询

时间:2019-04-10 00:23:05

标签: sql join self-join

我需要根据同一张表的内容查询一张表

当前,我在in中使用了and,这要花很多时间,而且我知道这不是最聪明的方法

PID CID Status
1   1   1
1   2   0
1   3   1
1   4   1
1   5   1
2   1   1
2   2   1
2   3   1
2   4   0
2   5   0

从上表中我需要满足以下组合的结果

Select PID from Tablename where 
(CID in (1) AND status 1)
AND
(CID in (2,3) AND status = 1)
AND
(CID in (4) AND status = 1)
AND 
(CID in (5) AND status = 1)

因此,按照上述要求,我应该仅获得PID 1

2 个答案:

答案 0 :(得分:1)

这应该获取所有选择语句中存在的所有PID:

SELECT PID FROM TableName WHERE CID = 1 AND Status = 1
INTERSECT
SELECT PID FROM TableName WHERE CID IN (2, 3) AND Status = 1
INTERSECT
SELECT PID FROM TableName WHERE CID = 4 AND Status = 1
INTERSECT
SELECT PID FROM TableName WHERE CID = 5 AND Status = 1

答案 1 :(得分:0)

您似乎想要:

Select PID
from Tablename 
where status = 1
group by PID
having sum(case when CID in (1) then 1 else 0 end) > 0 and
       sum(case when CID in (2, 3) then 1 else 0 end) > 0 and
       sum(case when CID in (4) then 1 else 0 end) > 0 and
       sum(case when CID in (5) then 1 else 0 end) > 0;

您的查询仅测试一行中的值。 where条件永远无法评估为真。

Here是一个db <>小提琴,表明此示例中的数据返回PID = 1。