select 计数查询

select count query

我有两个 table:

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
)

值是:

table a_b:

a_b_id   name 
  1      aaa
  2      bbb
  3      ccc

table一个:

a_b_id   status
  1      ACTIVE
  1      ACTIVE
  1      ACTIVE
  1      DELETED
  2      DELETED

然后我尝试 select 来自 table 'a_b' 的值以及来自 table '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

那么我必须如何修改我的查询才能收到我预期的结果?

您的 where 子句将您的 left join 变成 inner join。将条件放在 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

或者使用子查询来统计:

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;