How can I make SQL case sensitive string comparison on MySQL?

前端 未结 11 2191
温柔的废话
温柔的废话 2020-11-22 02:45

I have a function that returns five characters with mixed case. If I do a query on this string it will return the value regardless of case.

How can I make MySQL stri

11条回答
  •  旧巷少年郎
    2020-11-22 03:01

    The answer posted by Craig White has a big performance penalty

    SELECT *  FROM `table` WHERE BINARY `column` = 'value'
    

    because it doesn't use indexes. So, either you need to change the table collation like mention here https://dev.mysql.com/doc/refman/5.7/en/case-sensitivity.html.

    OR

    Easiest fix, you should use a BINARY of value.

    SELECT *  FROM `table` WHERE `column` = BINARY 'value'
    

    E.g.

    mysql> EXPLAIN SELECT * FROM temp1 WHERE BINARY col1 = "ABC" AND col2 = "DEF" ;
    +----+-------------+--------+------+---------------+------+---------+------+--------+-------------+
    | id | select_type | table  | type | possible_keys | key  | key_len | ref  | rows   | Extra       |
    +----+-------------+--------+------+---------------+------+---------+------+--------+-------------+
    |  1 | SIMPLE      | temp1  | ALL  | NULL          | NULL | NULL    | NULL | 190543 | Using where |
    +----+-------------+--------+------+---------------+------+---------+------+--------+-------------+
    

    VS

    mysql> EXPLAIN SELECT * FROM temp1 WHERE col1 = BINARY "ABC" AND col2 = "DEF" ;
    +----+-------------+-------+-------+---------------+---------------+---------+------+------+------------------------------------+
    | id | select_type | table | type  | possible_keys | key           | key_len | ref  | rows | Extra                              |
    +----+-------------+-------+-------+---------------+---------------+---------+------+------+------------------------------------+
    |  1 | SIMPLE      | temp1 | range | col1_2e9e898e | col1_2e9e898e | 93      | NULL |    2 | Using index condition; Using where |
    +----+-------------+-------+-------+---------------+---------------+---------+------+------+------------------------------------+
    enter code here
    

    1 row in set (0.00 sec)

提交回复
热议问题