我有两张桌子:
CREATE TABLE a_b
(
a_b_id integer NOT NULL,
name text NOT NULL
)
和
CREATE TABLE a
(
a_b_id integer NOT NULL,
status text NOT NULL
)
和值是:
a_b_id name
1 aaa
2 bbb
3 ccc
a_b_id status
1 ACTIVE
1 ACTIVE
1 ACTIVE
1 DELETED
2 DELETED
我尝试从表格中选择值' a_b'从表格中得到相关值的数量' a'没有' DELETED'状态。 我试图这样做:
select ab.name, count(a.a_b_id) from a_b ab left join a a on ab.a_b_id=a.a_b_id
where a.status != 'DELETED' GROUP BY ab.a_b_id,ab.name
但实际结果是:
aaa 3
预期结果是:
aaa 3
bbb 0
ccc 0
那么我如何修改我的查询以获得预期的结果呢?
答案 0 :(得分:2)
您的where
条款会将您的left join
变为inner join
。将条件放在联接的on
子句中
select ab.name,
count(a.a_b_id)
from a_b ab
left join a a on ab.a_b_id = a.a_b_id
and a.status != 'DELETED'
GROUP BY ab.a_b_id, ab.name
答案 1 :(得分:1)
或使用子查询来计算:
select a_b.name, (select count(*) from a
where a.a_b_id = a_b.a_b_id
and a.status != 'DELETED')
from a_b;