我有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
......但没有结果。看起来很简单,但对我来说是一个问题。
答案 0 :(得分: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
答案 1 :(得分:1)
这应该做:
SELECT COUNT(*)
FROM TableB AS B
WHERE EXISTS(SELECT 1 FROM TableA
WHERE id = B.id
AND value = 1)
答案 2 :(得分: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
答案 3 :(得分:0)
@MarcinJuraszek's answer的简化。如果可以信任外键,则无需加入表b
:
SELECT COUNT(DISTINCT a.b_id) AS cnt
FROM a
WHERE a.value = 1 ;