在MySQL中使用LIKE在SELECT案例中

时间:2016-08-02 23:17:46

标签: mysql sql case

我正在构建如下视图......

create view usersAndTickets as 
    select  tickets.subject as 'Name',
            'automatically imported ticket from former support web' as 'Description', 
            case tickets.department_id when 3 then 'Support' when 4 then 'Support' when 5 then 'Feature Request' when 2 then 'Sales' end as 'Type',
            case tickets.priority_id when 1 then 'Low' when 2 then 'Normal' when 3 then 'Urgent' end as 'Severity',
            case tickets.status_id when 1 then 'Under Review' when 2 then 'Closed' when 3 then 'Waiting on Customer' when 4 then 'New' when 7 then 'New' end as 'Status',
            users.email as 'EmailOfUserAssignedTo'
    from custom_fields_values, tickets, users where tickets.staff_id=users.id;

在视图中,我使用CASE WHEN ...特定值来用文本替换数字。

但我也有一个案例,我不想做一个严格的平等比较,而是我想做像......

case when custom_fields_values.value like '%Bar%' then 'Acme Product #1' end as 'Product',
case when custom_fields_values.value like '%Foo%' then 'Acme Product #2' end as 'Product',

但当然,MySQL抱怨产品'字段已存在。

那么我们如何使用CASE WHEN匹配函数(LIKE)而不是相等?

1 个答案:

答案 0 :(得分:4)

我认为你只需要case表达式中的多个子句:

(case when custom_fields_values.value like '%Bar%' then 'Acme Product #1' 
      when custom_fields_values.value like '%Foo%' then 'Acme Product #2'
 end) as Product,