1

我有一张看起来像这样的桌子

fID_a    fID_b
1        1
1        2
2        2
3        1

我想要所有fID_awherefID_b是 1 AND wherefID_a是该表中的单个记录。

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

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

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

4

5 回答 5

4

试试这个

SELECT fID_a FROM tbl
GROUP BY fID_a 
HAVING MAX(fID_b)=1
AND MIN(fID_b)=1
于 2013-07-08T12:10:36.820 回答
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
于 2013-07-08T12:05:55.803 回答
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
于 2013-07-08T12:20:34.333 回答
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;
于 2013-07-08T12:19:14.393 回答
-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
于 2013-07-08T12:17:15.523 回答