【发布时间】:2018-04-15 01:14:36
【问题描述】:
我有这个 PostgreSQL SQL 查询,用于从由 INNER JOIN 连接的 4 个表中选择几个值,但返回值有问题。
Select u.id,u.name,u.image,u.created_at as member_from,
p.referral, p.note,
CASE WHEN count(l.selfy_id)=NULL THEN '0' ELSE count(l.selfy_id) END as likes_total,
CASE WHEN count(s.id)=NULL THEN '0' ELSE count(s.id) END as selfies_total
from users as u
inner join profiles p on p.user_id = u.id
inner join selfies s on s.user_id = u.id
inner join likes l on l.selfy_id = s.id
where (u.active = true and s.active = true and u.id= 2 )
group by u.id,u.name,u.image,member_from,p.referral,p.note;
如果我在 where 块 s.active = true 中排除我会得到一些结果,但是当包含它时它不会返回任何内容。
在表格自拍中,我有 4 行有效的 true 和一个有效的 false 值。
解决方案是left join on likes 表。
【问题讨论】:
-
显然,没有一行包含所有三个值。我建议您提供示例数据(简化)和所需的结果。
-
是的,你是对的,喜欢表中缺少值,如果在 l.selfy_id = s.id 上使用左连接喜欢 l,那么它的返回值。谢谢!
-
顺便说一句,您不需要
CASE来处理空值。COUNT()不计算 null 所以将返回 0。另外count(s.id)=NULL是错误的,你不能使用等于运算符与 NULL 进行比较。你需要我们IS就像SomeValue IS NULL... 但正如我已经说过的COUNT()永远不会返回 null -
好的,谢谢,我会更新的。
标签: sql postgresql where-clause