如何用case-when-then编写一个mysql查询?

时间:2014-04-24 21:56:22

标签: mysql sql stored-procedures

有关如何运行以下查询的任何想法。我想我需要使用case-when-then以及group by子句。感谢

查找所有拥有' BASIC'包含至少(API,CUSTOM_WORKFLOW和FILE_UPLOAD)功能的版本或' TRIAL'包含atleast(API,CUSTOM_WORKFLOW)功能的版本

Customer table

id     name   edition       
---------------------
 1     CO1    BASIC
 2     CO2    TRIAL
 3     CO3    BASIC

Customer_Feature table

id  company_id   feature
------------------------
 1       1        API
 2       1        CUSTOM_WORKFLOW
 3       1        FILE_UPLOAD
 4       2        API
 5       2        CUSTOM_WORKFLOW
 6       2        FILE_SYNC
 7       3        API
 8       3        CUSTOM_WORKFLOW
 9       3        FILE_SYNC

这应仅返回ID为1和2的客户。

1 个答案:

答案 0 :(得分:3)

我不认为需要case声明。此查询使用聚合,因此可以为给定客户比较所有功能:

select c.id
from customers c join
     customer_feature cf
     on c.id = cf.company_id
group by c.id
having sum(c.edition = 'BASIC' and cf.feature in ('API', 'CUSTOM_WORKFLOW', 'FILE_UPLOAD')) = 3 or
       sum(c.edition = 'TRIAL' and cf.feature in ('API', 'CUSTOM_WORKFLOW')) = 2;

然后having子句查看每个版本匹配的相关功能的数量。这假设要素表中没有重复项 - 如果存在重复项,则查询将使用count(distinct)而不是sum()

编辑:

要使用count(distinct)获取结果,请执行以下操作:

having count(distinct case when c.edition = 'BASIC' and cf.feature in ('API', 'CUSTOM_WORKFLOW', 'FILE_UPLOAD') then df.feature end) = 3 or
       count(distinct case when c.edition = 'TRIAL' and cf.feature in ('API', 'CUSTOM_WORKFLOW') then cf.feature end) = 2;