简体   繁体   中英

MySQL: How to perform case-insensitive query

As far as I know LIKE operator should be case insensitive, but if I have the string "ABC Software" and I get the following query:

SELECT ...
FROM ...
WHERE ... LIKE 'AbC Softwa%'

I get a zero-rows result set (If I upper-case the second letter, the b, I get the right result). Why? Previously I had *utf8_bin* as character encoding, so I switch to *latin_swedish_ci*, supposing that binary matching was the source of all errors, but I get the same problem.

Try

SELECT ...
FROM ...
WHERE UPPER(...) LIKE 'ABC SOFTWA%'

MySQL is case-insensitive by default.

If you want to perform a case- sensitive search use:

SELECT ...
FROM ...
WHERE ... LIKE BINARY 'AbC Softwa%'

If your database, or table is configured to be case-sensitive by default, then to perform a case- insensitive search, you need to do something like this:

SELECT ...
FROM ...
WHERE ... COLLATE latin1_swedish_ci LIKE 'AbC Softwa%' COLLATE latin1_swedish_ci

If you are using utf8, then try this:

SELECT ...
FROM ...
WHERE ... COLLATE utf8_general_ci LIKE 'AbC Softwa%' COLLATE utf8_general_ci

You might want to investigate why your database is case-sensitive.

To see how the server is configured, run:

SHOW VARIABLES LIKE '%collation%';

To see the collation of your tables, run:

SHOW TABLE STATUS;

And to see the default collation for the database:

SHOW CREATE DATABASE dbname;

where dbname is the name of the database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM