我想知道,在p.amount is null
函数处写case .. when
更好,还是在WHERE
条款下写一下?
ONE:
select *,
case when p.amount is null then '1'
else (select count(1)
from Money_paid mp
where mp.post_id = p.id and mp.user_id = :user_id limit 1)
end paid
from Posts p
where p.id = :post_id
TWO:
select *,
(select count(1)
from Money_paid mp
where mp.post_id = p.id and
mp.user_id = :user_id and
p.amount is not null
limit 1) paid
from Posts p
where p.id = :post_id
那是哪一个?
答案 0 :(得分:1)
都不是。更好的方法是使用exists
:
select p.*,
(case when p.amount is null then 0 -- 0 seems more reasonable than 1
when exists (select 1
from Money_paid mp
where mp.post_id = p.id and mp.user_id = :user_id
)
then 1 else 0
end) as IsPaidFlag
from Posts p
where p.id = :post_id;
我倾向于采用单独的case
条件。这两个版本可能会优化到相同的结果。但是,具有外部相关性也可能会使优化器混淆。
答案 1 :(得分:1)
是否在IS NULL
或COALESCE
子句中使用WHERE
签入没有实际区别,但是,您应该将COUNT
替换为EXISTS
你只需要检查一个记录:
SELECT *,
CASE WHEN p.amount IS NULL THEN 1
ELSE
EXISTS
(
SELECT NULL
FROM money_paid
WHERE post_id = p.id
AND user_id = :user_id
)
END
FROM posts p
WHERE p.id = :post_id