简化多次使用的CASE表达式

时间:2015-02-20 00:27:13

标签: mysql

为了便于阅读,我想修改以下声明。有没有办法提取CASE语句,所以我可以多次使用它而不必每次都写出来?

select  
      mturk_worker.notes, 
      worker_id, 
      count(worker_id) answers, 
      count(episode_has_accepted_imdb_url) scored, 
      sum( case when isnull(imdb_url) and isnull(accepted_imdb_url) then 1 
                when imdb_url = accepted_imdb_url then 1 
                else 0 end ) correct, 
      100 * ( sum( case when isnull(imdb_url) and isnull(accepted_imdb_url) then 1 
                        when imdb_url = accepted_imdb_url then 1 
                        else 0 end) 
              / count(episode_has_accepted_imdb_url)  ) percentage
   from 
      mturk_completion 
         inner join mturk_worker using (worker_id) 
   where 
      timestamp > '2015-02-01' 
   group by 
      worker_id 
   order by 
      percentage desc, 
      correct desc

1 个答案:

答案 0 :(得分:1)

您实际上可以删除case语句。 MySQL将布尔表达式解释为数字上下文中的整数(1为真,0为假):

select mturk_worker.notes, worker_id, count(worker_id) answers, 
       count(episode_has_accepted_imdb_url) scored, 
       sum(imdb_url = accepted_imdb_url or imdb_url is null and accepted_idb_url is null) as correct, 
       (100 * sum(imdb_url = accepted_imdb_url or imdb_url is null and accepted_idb_url is null) / count(episode_has_accepted_imdb_url)
       ) as percentage
from mturk_completion inner join
     mturk_worker
     using (worker_id) 
where timestamp > '2015-02-01'
group by worker_id 
order by percentage desc, correct desc;

如果您愿意,可以使用null-safe equals运算符进一步简化它:

select mturk_worker.notes, worker_id, count(worker_id) answers, 
       count(episode_has_accepted_imdb_url) scored, 
       sum(imdb_url <=> accepted_imdb_url) as correct, 
       (100 * sum(imdb_url <=> accepted_imdb_url) / count(episode_has_accepted_imdb_url)
       ) as percentage
from mturk_completion inner join
     mturk_worker
     using (worker_id) 
where timestamp > '2015-02-01'
group by worker_id 
order by percentage desc, correct desc;

这不是标准的SQL,但它在MySQL中完全没问题。

否则,您需要使用子查询,并且MySQL中存在与子查询相关的额外开销。