MYSQL - IF列包含字符THEN ... ELSE

时间:2016-04-15 12:56:36

标签: mysql

我有一个可以包含下划线的列product_id。如果有,我想抓住它左边的所有内容,如下所示:

 SELECT LEFT(product_id,LOCATE('_',product_id) - 1) As po, product_id FROM orders_item

这会产生以下结果:

po     product_id   
40     40_59
46     46_74
95     95_223
134    134_271
86     86_265
71
76
48     48_79
137    137_298
50     50_247
48     48_80
124    124_187

但是它忽略了没有下划线的任何记录。如何在MySQL中编写以下内容?

 If `<contains underscore>` THEN `<everything to the left of the underscore>` ELSE `<entire field>`

2 个答案:

答案 0 :(得分:2)

改为使用SUBSTRING_INDEX

SELECT SUBSTRING_INDEX(product_id, '_', 1) AS po, product_id
FROM orders_item

答案 1 :(得分:0)

您可以使用CASE

SELECT
    CASE
        WHEN LOCATE('_', product_id) > 0 THEN LEFT(product_id, LOCATE('_', product_id) - 1)
        ELSE product_id
    END AS po,
    product_id
FROM
    orders_item