在CASE上设置一个条件.. WHEN vs WHERE子句?

时间:2016-04-13 12:20:40

标签: mysql

我想知道,在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

那是哪一个?

2 个答案:

答案 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 NULLCOALESCE子句中使用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