LoginSignup
3
3

More than 5 years have passed since last update.

[小ネタ]MySQL SQLでUTF8の4バイトを含む文字かどうか判別

Posted at

とりあえず簡単にやりたい場合に

クライアントがutf8の場合

select _utf8mb4'<判別したい文字列>' as result
$ mysql --default-character-set=utf8 -u <ユーザ名> -p -e "select _utf8mb4'寿司🍣' as result"
Enter password: 
+---------+
| result  |
+---------+
| 寿司?   |
+---------+

4バイト文字の部分が?になる。元の文字列と比較して一致しなければ4バイト文字を含むことに。
ただし、クライアントのcharacter-setがutf8mb4の場合は次の方法を使う。

クライアントがutf8mb4の場合

select convert(_utf8mb4'<判別したい文字列>' using utf8) as result
$ mysql --default-character-set=utf8mb4 -u <ユーザ名> -p -e "select convert(_utf8mb4'寿司🍣' using utf8) as result"
Enter password: 
+---------+
| result  |
+---------+
| 寿司?   |
+---------+
  • Booleanで結果を貰う場合(4バイト文字を含んでいれば1、含んでいなければ0)
$ mysql --default-character-set=utf8mb4 -u <ユーザ名> -p -e "select (convert(_utf8mb4'寿司🍣' using utf8) <> _utf8'寿司🍣') as result"
Enter password: 
+--------+
| result |
+--------+
|      1 |
+--------+

$ mysql --default-character-set=utf8mb4 -u <ユーザ名> -p -e "select (convert(_utf8mb4'寿司' using utf8) <> _utf8'寿司') as result"
Enter password: 
+--------+
| result |
+--------+
|      0 |
+--------+
3
3
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
3
3