1

我有 2 列a并且b具有 1:n 关系:

A.id, a.text, a.b_id(fk), a.value --
B.id(pk), b.text etc

我想创建一个返回数量的b.id查询count(a.value=1) > 0

我试过这个:

Select count(b.id)
from a.id
join b on a.b_id=b_id
group by b.id
having count(if(a.value=1),1,null))>0

...但没有结果。这看起来很简单,但对我来说是个问题。

4

4 回答 4

3

您不需要HAVING,因为标准联接无论如何INNER都不会返回b没有匹配行的行。a您也不需要GROUP BY-COUNT(DISTINCT )改用:

SELECT COUNT(DISTINCT b.id) AS cnt
FROM b
JOIN a ON a.b_id = b.id
WHERE a.value = 1
于 2013-09-02T20:44:07.743 回答
1

这应该这样做:

SELECT COUNT(*)
FROM TableB AS B
WHERE EXISTS(SELECT 1 FROM TableA
             WHERE id = B.id
             AND value = 1)
于 2013-09-02T20:46:23.240 回答
0

试试这个:-

Select count(b.id) as x
FROM b
JOIN a ON a.b_id = b.id
WHERE a.value = 1
group by b.id
于 2013-09-02T20:44:36.203 回答
0

@MarcinJuraszek 的答案的简化。如果可以信任外键,则无需加入表b

SELECT COUNT(DISTINCT a.b_id) AS cnt
FROM a
WHERE a.value = 1 ;
于 2013-09-02T23:20:22.023 回答