How do I convert a column to ASCII on the fly without saving to check for matches with an external ASCII string?

前端 未结 4 1361
夕颜
夕颜 2021-01-19 09:25

I have a member search function where you can give parts of names and the return should be all members having at least one of username, firstname or lastname matching that i

4条回答
  •  北恋
    北恋 (楼主)
    2021-01-19 09:45

    @vincebowdren answer above works, I'm just adding this as an answer for formatting purposes:

    CREATE TABLE `members` (
      `id` int(11) DEFAULT NULL,
      `lastname` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL
    );
    insert into members values (1, 'test6ë');
    select id from members where lastname like 'test6e%';

    Yields

    +------+
    | id   |
    +------+
    |    1 |
    +------+

    And using Latin1,

    set names latin1;
    CREATE TABLE `members2` (
      `id` int(11) DEFAULT NULL,
      `lastname` varchar(20) CHARACTER SET latin1 DEFAULT NULL
    );
    insert into members2 values (1, 'Renée');
    select id from members2 where lastname like '%Renee%';

    will yield:

    +------+
    | id   |
    +------+
    |    1 |
    +------+

    Of course, the OP should have the same charset in the application (PHP), connection (MySQL on Linux used to default to latin1 in 5.0, but defaults to UTF8 in 5.1), and in the field datatype to have less unknowns. Collations take care of the rest.

    EDIT: I wrote should to have a better control over everything, but the following also works:

    set names latin1;
    select id from members where lastname like 'test6ë%';

    Because, once the connection charset is set, MySQL does the conversion internally. In this case, it will convert somehow convert and compare the UTF8 string (from DB) to the latin1 (from query).

    EDIT 2: Some skepticism requires me to provide an even more convincing example:

    Given the statements above, here what I did more. Make sure the terminal is in UTF8.

    set names utf8;
    insert into members values (5, 'Renée'), (6, 'Renêe'), (7, 'Renèe');
    select members.id, members.lastname, members2.id, members2.lastname
    from members inner join members2 using (lastname);

    Remember that members is in utf8 and members2 is in latin1.

    +------+----------+------+----------+
    | id   | lastname | id   | lastname |
    +------+----------+------+----------+
    |    5 | Renée    |    1 | Renée    |
    |    6 | Renêe    |    1 | Renée    |
    |    7 | Renèe    |    1 | Renée    |
    +------+----------+------+----------+

    which proves with the correct settings, the collation does the work for you.

提交回复
热议问题