用左联接计数

时间:2019-07-13 02:02:50

标签: sql postgresql postgresql-10

我已经编写了此SQL(有效):

with mark_derek as (
  select rachel_id
  from chad_patrick cp
  where cp.name in ('p_mark', 'p_derek')
)
select r.id as rachel_id,
       count(md.rachel_id) as total
from rachel r
     left join mark_derek md on md.rachel_id = r.id
group by r.id;

左联接很重要,因为对于未联接的任何事物,返回的total列应为0。

我尝试通过将cp.name in更改为cp.name is null or cp.name in来尝试容纳左连接,以使其不使用CTE,但它没有用。如果左连接失败,似乎is null被忽略了,而该行被忽略了。

是否可以解决此问题,从而不需要子查询或CTE?

1 个答案:

答案 0 :(得分:1)

您可以像这样消除CTE:

select r.id as rachel_id, count(cp.rachel_id) as total
from rachel r left join
     chad_patrick cp
     on cp.rachel_id = r.id and
        cp.name in ('p_mark', 'p_derek')
group by r.id;

过滤条件需要放在on子句中。