
大家好,我遇到了一个奇怪的 SQL 问题,关于 mysql 下同时使用 UUID()和 REPLACE()函数会发生重复的问题。
UUID()会生成 36 个字符,有时候需要 32 个字符就需要把- 去掉,通常会写成REPLAC(UUID(), "-", ""),这次我遇到了 100%出现重复的现象。
下面是我测试的 SQL,可以清楚描述这个问题。
select version() as 'mysql version'; show variables like "%char%"; DROP TABLE IF EXISTS mtest1; CREATE TABLE mtest1 ( f varchar(10) ); INSERT INTO mtest1 (f) VALUES ("lily"); INSERT INTO mtest1 (f) VALUES ("lucy"); SELECT UUID() as uuid, f from mtest1; SELECT REPLACE(UUID(), "-", "") as uuid, f from mtest1; 结果如下:
mysql version 1 5.7.12-log Variable_name Value 1 character_set_client utf8mb4 2 character_set_connection utf8mb4 3 character_set_database utf8 4 character_set_filesystem binary 5 character_set_results utf8mb4 6 character_set_server utf8 7 character_set_system utf8 8 character_sets_dir C:\Program Files\MySQL\MySQL Server 5.7\share\charsets\ uuid f 1 36ea391f-fcbe-11e7-b0df-001c42c9112f lily 2 36ea398f-fcbe-11e7-b0df-001c42c9112f lucy uuid f 1 36ea3e0ffcbe11e7b0df001c42c9112f lily 2 36ea3e0ffcbe11e7b0df001c42c9112f lucy 这里 uuid 发生重复。 查到了一些网友的博客说改字符集就可以,但是原因不清楚。
http://blog.csdn.net/hgg923/article/details/76643288
http://blog.csdn.net/lwjdear/article/details/73187645
http://www.cnblogs.com/tibit/p/6183864.html
http://blog.csdn.net/LWJdear/article/details/73187656
使用set names "utf8"改字符集:
select version() as 'mysql version'; set names "utf8"; show variables like "%char%"; DROP TABLE IF EXISTS mtest1; CREATE TABLE mtest1 ( f varchar(10) ); INSERT INTO mtest1 (f) VALUES ("lily"); INSERT INTO mtest1 (f) VALUES ("lucy"); -- SELECT UUID(), f from mtest1; SELECT UUID() as uuid, f from mtest1; SELECT REPLACE(UUID(), "-", "") as uuid, f from mtest1; 结果:
mysql version 1 5.7.12-log Variable_name Value 1 character_set_client utf8 2 character_set_connection utf8 3 character_set_database utf8 4 character_set_filesystem binary 5 character_set_results utf8 6 character_set_server utf8 7 character_set_system utf8 8 character_sets_dir C:\Program Files\MySQL\MySQL Server 5.7\share\charsets\ uuid f 1 ac12a0a6-fcbf-11e7-b0df-001c42c9112f lily 2 ac12a0e6-fcbf-11e7-b0df-001c42c9112f lucy uuid f 1 ac12a8e7fcbf11e7b0df001c42c9112f lily 2 ac12a921fcbf11e7b0df001c42c9112f lucy 这里产生 uuid 不重复。 如果不改字符集,把 uuid()的结果 insert 一个临时表里,select 这个临时表时用 replace 也不会出问题。
但是一旦在 utfmb4 字符集下,replace 和 uuid 一起用,就会重复。
哪位高手知道这是为什么吗?