像MySQL中的Case敏感

时间:2011-11-10 17:07:37

标签: mysql case-sensitive sql-like

我有一个MySQL查询:

SELECT concat_ws(title,description) as concatenated HAVING concatenated LIKE '%SearchTerm%';

我的表格用myISAM编码utf8_general_ci。

搜索似乎区分大小写。

我无法弄清楚如何修复它。出了什么问题和/或我该如何解决?

8 个答案:

答案 0 :(得分:41)

在性能方面更好的解决方案:

SELECT .... FROM .... WHERE `concatenated` LIKE BINARY '%SearchTerm%';

当任何操作数是二进制字符串时,字符串比较区分大小写。

另一种方法是使用COLLATE

SELECT ....
FROM ....
WHERE `concatenated` like '%SearchTerm%' COLLATE utf8_bin;

答案 1 :(得分:18)

试试这个:

SELECT LOWER(CONCAT_WS(title,description)) AS concatenated 
WHERE concatenated LIKE '%searchterm%'

或(让你看到差异)

SELECT LOWER(CONCAT_WS(title,description)) AS concatenated 
WHERE concatenated LIKE LOWER('%SearchTerm%')

答案 2 :(得分:5)

在此方法中,您不必选择搜索的字段:

SELECT table.id 
FROM table
WHERE LOWER(table.aTextField) LIKE LOWER('%SearchAnything%')

答案 3 :(得分:0)

这也有效:

SELECT LOWER(DisplayName) as DN
FROM   Bidders
WHERE  OrgID=45
HAVING DN like "cbbautos%"
LIMIT  10;

答案 4 :(得分:0)

检查表架构中提到的CHARSET:

show create table xyz;

基于CHARSET,您可以尝试以下方法。

select name from xyz where name like '%Man%' COLLATE latin1_bin;
select name from xyz where name like '%Man%' COLLATE utf8_bin;

以下是适用于我的案例,CHARSET = latin1,MySQL版本= 5.6。

mysql> select installsrc from appuser where installsrc IS NOT NULL and installsrc like 'Promo%' collate latin1_bin limit 1;
+-----------------------+
| installsrc            |
+-----------------------+
| PromoBalance_SMS,null |
+-----------------------+
1 row in set (0.01 sec)

mysql>
mysql> select installsrc from appuser where installsrc IS NOT NULL and installsrc like 'PROMO%' collate latin1_bin limit 1;
+---------------------------+
| installsrc                |
+---------------------------+
| PROMO_SMS_MISSEDCALL,null |
+---------------------------+
1 row in set (0.00 sec)

mysql> select installsrc from appuser where installsrc IS NOT NULL and installsrc like 'PROMO%' limit 1;
+-----------------------+
| installsrc            |
+-----------------------+
| PromoBalance_SMS,null |
+-----------------------+
1 row in set (0.01 sec)

答案 5 :(得分:0)

只是为了完成,如果有帮助:

https://dev.mysql.com/doc/refman/5.7/en/case-sensitivity.html所述,对于默认字符集,非二进制字符串比较默认情况下不区分大小写。

因此,执行不区分大小写的比较的简单方法是将字段转换为CHAR,VARCHAR或TEXT类型。

以下是针对单个字段进行检查的示例:

SELECT * FROM table1 WHERE CAST(`field1` AS CHAR) LIKE '%needle%';

答案 6 :(得分:-1)

这是工作代码:

SELECT title,description
FROM (
 SELECT title,description, LOWER(CONCAT_WS(title,description)) AS concatenated
 FROM table1 
) AS Q
WHERE concatenated LIKE LOWER('%search%') 

答案 7 :(得分:-1)

由于表中使用的排序规则,在这种情况下会出现此问题。您已使用utf8_general_ci作为排序规则。如果排序规则更改为utf8_general_ci,则搜索不会区分大小写。 因此,一种可能的解决方案是更改排序规则。