在SQL中count = 1时选择不同的值

时间:2013-07-08 12:04:16

标签: sql select group-by having-clause

我有一张看起来像这样的表

fID_a    fID_b
1        1
1        2
2        2
3        1

我希望所有fID_a fID_b为1,其中fID_a是该表中的单个记录。

我有一个看起来像这样的SQL查询

select fID_a from tbl 
 where fID_b = 1 
 group by fID_a 
having count(*) = 1

但该查询仍包含fID_a 1,即使该表中有2条记录!

5 个答案:

答案 0 :(得分:4)

试试这个

SELECT fID_a FROM tbl
GROUP BY fID_a 
HAVING MAX(fID_b)=1
AND MIN(fID_b)=1

答案 1 :(得分:2)

如果你使用where条款,那么你会过滤掉会导致count不准确的其他值。

select fID_a 
from tbl  
group by fID_a 
having count(*) = 1 
and sum(case when fID_b = 1 then 1 else 0 end) = 1

答案 2 :(得分:2)

你应该尝试自我加入来实现这个目标:

SELECT t1.fID_a 
  FROM tbl t1
  JOIN tbl t2
    ON t1.fid_a = t2.fid_a
   AND t1.fid_b = 1
 GROUP BY t1.fID_a 
HAVING COUNT(*) = 1

答案 3 :(得分:0)

select fID_a,fID_b 
from tb1, (select fID_a 
             from tb1 
         group by fID_a 
           having count(*) = 1) temp
where tb1.fID_a = temp.fID_a
and fID_b = 1;

答案 4 :(得分:-1)

这应该有效。您的查询不起作用,因为mysql在有子句之前计算where子句。

select fID_a from 
       (select fID_a, fID_b 
        from tbl 
        group by fID_a 
        having count(*) = 1) temp 
where fID_b = 1