WHERE 和 AND 子句不是 return 值

WHERE and AND clause not return values

我有这个 PostgreSQL SQL 查询从 4 table 中选择几个值,通过 INNER JOIN 连接,我在返回值时遇到问题。

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;

如果我在 wheres.active = true 中排除,我会得到一些结果,但当包含它时,它不是 returns 任何东西。

在 table 的自拍中,我有 4 行为 true,1 行为 active false。

解决方案是 left join on likes table。

这对于评论来说太长了,而且与所问的问题无关(这显然是使用 left join 解决的)。

COUNT() 永远不会 returns NULL 值。并且 CASE 表达式仅 returns 具有单一类型的单一值。并且,基本上所有与 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 

现在,这些将成为 return 完全相同的值,因为 COUNT() 计算非 NULL 值并且 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 是正确的。