区分大小写的字符串出现

时间:2018-03-19 20:11:33

标签: mysql case-sensitive

我使用以下查询来拆分列值。它适用于不区分大小写的场景,但我希望它能区分大小写。

例如,在字符串'Oil is a product Ingredients are'中,如果我的搜索关键字是'成分',它应该返回false,如果搜索关键字是'Ingredients',则只返回true。 mysql中有没有允许这个的功能吗?

SELECT 
  SUBSTRING_INDEX(description, 'Ingredients', 1),
    if(LOCATE('Ingredients', description)>0, SUBSTRING_INDEX(description, 'Ingredients', -1), '')
FROM `product`

1 个答案:

答案 0 :(得分:1)

来自mysql的 LOCATE 功能的文档:

  

此函数是多字节安全的,仅在at时区分大小写   至少一个参数是二进制字符串。

也就是说,您需要cast / convert您的参数来执行区分大小写的匹配。

例如:如果您的第一条记录为Oil is a product Ingredients are...,而您的第二条记录为Oil is a product ingredients are...,则以下查询:

SELECT 
  LOCATE('ingredients', description) AS match_both_1,
  LOCATE('Ingredients', description) AS match_both_2,
  LOCATE(CAST('ingredients' AS BINARY), CAST(description AS BINARY)) AS match_second,
  LOCATE(CAST('Ingredients' AS BINARY), CAST(description AS BINARY)) AS match_first
FROM product

会给你预期的结果:

| match_both_1 | match_both_2 | match_second | match_first |
|     18       |     18       |      0       |     18      |
|     18       |     18       |     18       |      0      |

请参阅 DEMO