MYSQL IF字段包含这使得其他字段

时间:2012-12-11 16:35:30

标签: mysql if-statement concatenation case

我的table1中有一个名为ITEM的字段。如果ITEM包含%USED-%(USED-),那么我想将其设为TIER1 Used Restaurant Equipment ,以便相应地进行分组。

这是我目前的陈述,如何通过IFCASE实现上述目标?

select 
    CT.TIER1, CT.TIER2
from
    trx.table1 MT
        LEFT JOIN
    trx.table2 CT1 ON MT.ITEM = CT1.ITEM
        LEFT JOIN
    trx.table3 CT ON CT1.WEB_NUM = CT.WEBNUMBER
GROUP BY CT.TIER1
LIMIT 0 , 15

当前输出:

TIER1                   TIER2
NULL                    NULL
Business Type           Ice Cream Equipment
Chinese Food Equipment  Ricers
Concession Equipment    Concession Accessories
Cooking Equipment       Fryers
Food Preparation        Food Preparation Supplies
Food Storage            Storage Racks
Food Warming Equipment  Hot Food Wells

我希望仍然有一些NULL Tier1和Tier2,但我希望它也将TIER1显示为'二手餐厅设备',类似于:

TIER1                      TIER2
NULL                       NULL
Used Restaurant Equipment  NULL
Business Type              Ice Cream Equipment
Chinese Food Equipment     Ricers
Concession Equipment       Concession 

2 个答案:

答案 0 :(得分:6)

这应该是你要找的东西:

   SELECT
       IF (MT.ITEM LIKE '%USED-%', 'Used Restaurant Equipment', CT.TIER1) AS TIER1,
       CT.TIER2
   FROM
       trx.table1 MT
           LEFT JOIN
       trx.table2 CT1 ON MT.ITEM = CT1.ITEM
           LEFT JOIN
       trx.table3 CT ON CT1.WEB_NUM = CT.WEBNUMBER
   GROUP BY
       IF (MT.ITEM LIKE '%USED-%', 'Used Restaurant Equipment', CT.TIER1)
   LIMIT 0 , 15

答案 1 :(得分:0)

如果您不尝试重新定义tier1,而是创建一个新的列,从tier1或常量“Used Restaurant Equipment”获取其值,则最容易实现。然后,您可以按照用于创建新列的相同条件进行分组,因为group by子句可以是完整表达式。