我有这个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和1行具有有效的false值。
解决方案是left join on likes
表。
该时间太长,无法发表评论,与提出的问题无关(显然已使用来解决left join
)。
COUNT()
从不返回NULL
值。和CASE
表达仅返回与单一类型的单个值。并且,基本上所有对NULL
return的比较NULL
都被视为FALSE。鉴于这些事实,您能说出这种表达方式有三点错误吗?
CASE WHEN count(l.selfy_id)=NULL THEN '0' ELSE count(l.selfy_id) END as likes_total,
您可以将公式表示SELECT
为:
Select u.id, u.name, u.image, u.created_at as member_from,
p.referral, p.note,
count(l.selfy_id) as likes_total, count(s.id) as selfies_total
现在,这些将返回完全相同的值,因为COUNT()
对非NULL值进行计数并且to的两个参数COUNT()
都在JOIN
条件中使用-永不NULL
。
我推测您确实打算:
Select u.id, u.name, u.image, u.created_at as member_from,
p.referral, p.note,
count(distinct l.selfy_id) as likes_total,
count(distinct s.id) as selfies_total
尽管我不是100%肯定这些ID是正确的计数。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句