LoginSignup
2
2

More than 5 years have passed since last update.

MySQLでutf8mb4のマルチバイト文字を置換する

Last updated at Posted at 2015-05-27

前提

MySQLのcharsetをutf8mb4に設定しておくとマルチバイト文字を保存することができます。
しかし、クライアント側の環境でマルチバイト文字を扱えない場合、SQL中に埋め込むことができなかったりします。

mysql> select name from user;

+-----------+
| name      |
+-----------+
| 𠮷田       |
+-----------+
| 尾𥔎       |
+-----------+

mysql> select replace(name, 'ð ®·', '吉') from user;

+-----------------------------+
| replace(name, 'ð ®·', '吉') |
+-----------------------------+
| 𠮷田                        |
+-----------------------------+
| 尾𥔎                        |
+-----------------------------+

解決方法

この場合、いったんhex関数で16進数のコードを取得して、0x〜のリテラルで文字を指定すればSQLに埋め込むことができます。

mysql> select hex(name) from user;

+----------------+
| hex(name)      |
+----------------+
| F0A0AEB7E794B0 |
+----------------+
| E5B0BEF0A5948E |
+----------------+

mysql> select replace(name, 0xF0A0AEB7, '吉') from user;

+---------------------------------+
| replace(name, 0xF0A0AEB7, '吉') |
+---------------------------------+
| 吉田                            |
+---------------------------------+
| 尾𥔎                            |
+---------------------------------+
2
2
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
2