2016-07-20 239 views
0

我正在创建数据分析仪表板。我将一个名为channel_param的参数传递给MySQL数据源。基于mySQL IF-ELSE条件选择两个MySQL select查询

我想补充的,如果在这个查询语句首先检查channel_param参数值等于“ALL”

在“ALL”的情况下,下面的查询应执行:

SELECT 
c.CountryCode, COUNT(f.`country_code_id`) AS view_count 
FROM 
fact_access_logs_views f 
JOIN dim_country_code c ON f.`country_code_id` = c.`country_code_id` 
JOIN dim_time_access d ON f.`access_time_id` = f.`access_time_id` 
JOIN dim_channel chn ON f.`channel_id` = chn.`channel_id 

在任何其他价值的情况下,该查询应执行:

SELECT 
c.CountryCode, COUNT(f.`country_code_id`) AS view_count 
FROM 
fact_access_logs_views f 
JOIN dim_country_code c ON f.`country_code_id` = c.`country_code_id` 
JOIN dim_time_access d ON f.`access_time_id` = f.`access_time_id` 
JOIN dim_channel chn ON f.`channel_id` = chn.`channel_id` 
WHERE 
chn.`shortname_chn` = ${channel_param} 

我怎样才能做到这一点?

+0

Mysql确实有IF()[refrence](http://stackoverflow.com/a/15265944/2586617) –

回答

0

这就是我使用SQL CASE表达式解决问题的方法。

SELECT c.CountryCode, COUNT(f.`country_code_id`) AS view_count FROM fact_access_logs_views f 
    JOIN dim_country_code c ON f.`country_code_id` = c.`country_code_id` 
    JOIN dim_time_access d ON f.`access_time_id` = f.`access_time_id` 
    JOIN dim_channel chn ON f.`channel_id` = chn.`channel_id` 
WHERE chn.`shortname_chn` LIKE 
CASE WHEN 
     ${channel_param} = "ALL" THEN '%%' ELSE ${channel_param} 
END 

我希望这个答案有助于将来面对同样困惑的人。