LoginSignup
2
0

MySQLで全角+半角の文字列検索がうまくいかない

Posted at

事象

MySQLで全角、半角が入り混じった文字列を検索した際、狙ったデータが取得できずハマってしまった。。

テーブル

id name memo
1 半角スペース+文字列+半角スペース
2  あ  全角スペース+文字列+全角スペース
3 半角スペース+文字列
4  あ 全角スペース+文字列

SQL(半角スペース+文字列)

SELECT * FROM user_table WHERE name = " あ"

想定

id name memo
3 半角スペース+文字列

結果

id name memo
1 半角スペース+文字列+半角スペース
2  あ  全角スペース+文字列+全角スペース
3 半角スペース+文字列
4  あ 全角スペース+文字列

①半角スペースと全角スペースが区別されていない
②末尾のスペースが無視されている

原因

照合順序が「utf8mb4_unicode_ci」だったため
①大文字小文字区別しない/半角全角を区別しない
②pad属性が「PAD SPACE」つまり末尾のスペースが無視される

解決策

照合順序を「utf8mb4_bin」に変更したら意図した検索結果になった
末尾のスペースが無視される問題のみ解決したい場合は、演算子に「LIKE」を使うことで正確な文字列比較をしてくれる

参照元

照合順序
https://www.wakuwakubank.com/posts/797-mysql-collation/

pad属性
https://dev.mysql.com/doc/refman/8.0/ja/charset-binary-collations.html#charset-binary-collations-trailing-space-comparisons

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0