SQL - 需要帮助过滤基于行的结果

时间:2011-05-17 01:25:10

标签: sql

我有一个看起来像这样的表:

p_id | comp_id
-----+--------
 100 | 1
 100 | 2
 101 | 1   
 102 | 1

基本上,p_id可以根据需要在表格中多次输入comp_id

我需要的是选择p_id 1和2上的所有comp_id。在上表中,这意味着只会返回p_id == 100

有一种有效的方法吗?

6 个答案:

答案 0 :(得分:3)

SELECT p_id
FROM Mytable
WHERE comp_id IN (1,2)
GROUP BY p_id
HAVING COUNT(distinct comp_id) = 2

确保IN包含与HAVING子句中的int相同数量的值。

答案 1 :(得分:1)

这个怎么样:

SELECT t1.p_id
FROM table AS t1
INNER JOIN table AS t2 ON t1.p_id = t2.p_id
WHERE t1.comp_id=1
AND t2.comp_id=2

答案 2 :(得分:1)

SELECT p_id
  FROM table 
 WHERE comp_id in (1,2)
 GROUP BY p_id
HAVING COUNT(DISTINCT comp_id) = 2

assumig #t是下表(你要搜索的comp_id):

comp_id
-------
      1
      2

SELECT t1.p_id
  FROM table t1
 WHERE NOT EXITS (SELECT NULL
                    FROM table t2
              RIGHT JOIN #t
                      ON t2.p_id    = t1.p_id
                     AND t2.comp_id = #t.comp_id
                   WHERE t2.comp_id IS NULL)

答案 3 :(得分:0)

SELECT p_id
FROM TABLE 
WHERE EXISTS (SELECT P_ID from TABLE where comp_id=1) and EXISTS (SELECT P_ID from TABLE where comp_id=2)

答案 4 :(得分:0)

select distinct p_id from table a 
    inner join table b on a.p_id = b.p_id where a.p_id = 1 and b.p_id = 2

这种方式可能会起作用但看起来效率很低

答案 5 :(得分:0)

 SELECT p_id FROM tbl WHERE EXISTS
 (SELECT p_id FROM tbl WHERE comp_id = 1)
 AND EXISTS (SELECT p_id FROM tbl WHERE comp_id = 2)