2016-07-20 181 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 

我希望這個答案有助於將來面對同樣困惑的人。