我有一列 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>`
最佳答案
使用SUBSTRING_INDEX
相反:
SELECT SUBSTRING_INDEX(product_id, '_', 1) AS po, product_id
FROM orders_item
关于MYSQL - 如果列包含字符 THEN ... ELSE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36647786/