嵌套case语句逻辑

kx1ctssn  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(425)

我正在处理一个查询,以平展wordpress数据库中的一些wp\u postsmeta数据,并需要为各种meta\u值设置一个特定值。我有一个类别键和各种类别值,对于每个值,我想为我们的品牌调色板设置一个名为color的列和一个名为color的列

select post_title as title, 
 MAX(CASE WHEN meta_key='corporate_calendar_category' THEN meta_value END) as 'category',
 MAX(CASE WHEN meta_key = 'corporate_calendar_subcategory' THEN meta_value END) as 'subcategory',

 // Do I need to include a nested CASE WHEN?
 MAX(CASE WHEN meta_key = 'corporate_calendar_subcategory' and meta_value = 'Marketing' THEN 'blueLagoon' END) as 'color',

 MAX(CASE WHEN meta_key = 'corporate_calendar_presenter' THEN meta_value END) as 'presenter',
 MAX(CASE WHEN meta_key = 'corporate_calendar_date' THEN meta_value END) as 'start_date',
 MAX(CASE WHEN meta_key = 'corporate_calendar_time' THEN meta_value END) as 'start_time',
 MAX(CASE WHEN meta_key = 'corporate_calendar_duration' THEN meta_value END) as 'duration',
 MAX(CASE WHEN meta_key = 'corporate_calendar_registration_link' THEN meta_value END) as 'registration_link',
 MAX(CASE WHEN meta_key = 'corporate_calendar_description' THEN meta_value END) as 'description',
 MAX(CASE WHEN meta_key = 'corporate_calendar_image_path' THEN meta_value END) as 'image_path'

FROM   wp_posts p 
JOIN wp_postmeta m ON p.id = m.post_id
where p.post_type = 'calendar-event'
and p.post_status = 'publish'
GROUP BY p.id

“公司日历”子类别有许多值,“市场营销”、“人力资源”、“公司假日”等,对于每个子类别,我希望每一行都有特定的颜色。

title     category   subcategory       color        presenter   start_date etc.
Example   Training   Marketing         blueLagoon   someone     08/29/2018
Labor Day Reminder   Company Holiday   camelot                  09/03/2018
etc
etc

实现这一点的最佳方法是在针对meta\ u值时使用嵌套case吗?还是有更好的办法?
我也尝试过包含if语句(如下),但每行都重复。

if(meta_key = 'corporate_calendar_subcategory', 
 CASE
   WHEN meta_value = 'Marketing' THEn 'blueLagoon'
   WHEN meta_value = 'Company Holiday' THEN 'camelot'
 END,
 '') as color,
ldioqlga

ldioqlga1#

是的,嵌套的 CASE 声明将是正确的方式,如果你知道所有的类别和颜色事先。如果类别颜色在另一个表中,则可以执行子选择或 JOIN 相反。
下面是一个嵌套case的示例:

max(case when meta_key = 'corporate_calendar_subcategory' then
    case meta_value
        when 'Marketing' then 'blue'
        when 'Sales' then 'yellow
        when 'Development' then 'red'
    end
end)

相关问题