右连接不选择null

时间:2016-08-17 17:26:34

标签: sql postgresql

我正在尝试根据日期汇总一些指标。问题是只选择了匹配关联的日期。我想要完整的日期范围,0表示没有匹配的关联。

我正在尝试这个

SELECT f2."day", coalesce(count(c0."id"), 0) 
FROM "conversations" AS c0 
LEFT OUTER JOIN "apps" AS a1 ON a1."id" = c0."app_id" 
RIGHT OUTER JOIN ((SELECT now()::date - d AS day FROM generate_series (0, 10) d)) AS f2 ON f2."day" = c0."inserted_at"::date 
WHERE (a1."id" = 'ASnYW1-RgCl0I')
GROUP BY f2."day"

1 个答案:

答案 0 :(得分:3)

使您的where子句成为连接条件的一部分。以下代码将应用程序上的左连接转换为内连接

SELECT f2."day", coalesce(count(c0."id"), 0) 
FROM "conversations" AS c0 
LEFT OUTER JOIN "apps" AS a1 ON a1."id" = c0."app_id" 
RIGHT OUTER JOIN ((SELECT now()::date - d AS day FROM generate_series (0, 10) d)) AS f2 ON f2."day" = c0."inserted_at"::date 
WHERE (a1."id" = 'ASnYW1-RgCl0I')
GROUP BY f2."day"

此代码不会:

SELECT f2."day", coalesce(count(c0."id"), 0) 
FROM "conversations" AS c0 
LEFT OUTER JOIN "apps" AS a1 ON a1."id" = c0."app_id"  and  (a1."id" = 'ASnYW1-RgCl0I')
RIGHT OUTER JOIN ((SELECT now()::date - d AS day FROM generate_series (0, 10) d)) AS f2 ON f2."day" = c0."inserted_at"::date 
GROUP BY f2."day"