2016-07-20 14 views
0

データ解析ダッシュボードを作成しています。channel_paramという名前のパラメータをMySQLデータソースに渡します。mySQL IF-ELSE条件に基づいて2つのMySQL選択クエリを選択してください

私はchannel_paramパラメータの値が「ALL」の場合は「ALL」

をと等しい場合、最初のチェックは、次のクエリが実行すべきことは、このクエリではif文を追加します:

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 

私は、この回答が今後も同じ混乱に直面するのに役立つことを願っています。

関連する問題