MYSQL使用REGEXP实现用户列表首字母检索

需要实现客户列表界面显示用户首字母检索

数据库使用的字符集是:utf8mb4,因为要存储用户昵称,昵称中包含特殊符号

原sql如下:

 select
        lower(CONVERT(case when from_base64(u.nickname) REGEXP '^[a-zA-Z]' then LEFT(from_base64(u.nickname), 1)
        when from_base64(u.nickname) REGEXP '^[0-9]' then LEFT(from_base64(u.nickname), null)
        else ELT(INTERVAL(CONV(HEX(LEFT(CONVERT(CONVERT(from_base64(u.nickname),CHAR(1000) CHARACTER SET utf8) USING gbk),1)),16,10),
        0xB0A1,0xB0C5,0xB2C1,0xB4EE,0xB6EA,0xB7A2,0xB8C1,0xB9FE,0xBBF7,
        0xBFA6,0xC0AC,0xC2E8,0xC4C3,0xC5B6,0xC5BE,0xC6DA,0xC8BB,0xC8F6,
        0xCBFA,0xCDDA,0xCEF4,0xD1B9,0xD4D1),
        'A','B','C','D','E','F','G','H','J','K','L','M','N','O','P',
        'Q','R','S','T','W','X','Y','Z') end,CHAR(1000) CHARACTER SET utf8)) firstChar,
        LEFT(CONVERT(from_base64(u.nickname),CHAR(1000) CHARACTER SET utf8),1) firstWord
     .......

执行报错:Character set 'binary' cannot be used in conjunction with 'utf8mb4_0900_ai_ci' in call to regexp_like.

猜测是字符集的问题,通过CONVERT函数将需要通过正则匹配的字符转成gbk,修改后sql如下:

select lower(CONVERT(case
	 when
LEFT ( CONVERT ( from_base64 ( u.nickname ), CHAR ( 1000 ) CHARACTER SET gbk ), 1 ) REGEXP '^[a-zA-Z]'
			 then LEFT(from_base64(u.nickname), null)
	 when
LEFT ( CONVERT ( from_base64 ( u.nickname ), CHAR ( 1000 ) CHARACTER SET gbk ), 1 ) REGEXP '^[0-9]'
			 then LEFT(from_base64(u.nickname), 1)
	 else ELT(INTERVAL (CONV(HEX(LEFT(
					 CONVERT(CONVERT(from_base64(u.nickname), CHAR(1000) CHARACTER SET utf8) USING gbk),
					 1)), 16, 10), 0xB0A1, 0xB0C5, 0xB2C1, 0xB4EE, 0xB6EA, 0xB7A2, 0xB8C1, 0xB9FE, 0xBBF7,
											0xBFA6, 0xC0AC, 0xC2E8, 0xC4C3, 0xC5B6, 0xC5BE, 0xC6DA, 0xC8BB, 0xC8F6,
											0xCBFA, 0xCDDA, 0xCEF4, 0xD1B9, 0xD4D1), 'A', 'B', 'C', 'D', 'E', 'F', 'G',
						'H', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'W', 'X', 'Y',
						'Z') end, CHAR(1000) CHARACTER SET utf8))     firstChar,
LEFT(CONVERT(from_base64(u.nickname), CHAR(1000) CHARACTER SET utf8mb4), 1) firstWord,
CONVERT(from_base64(u.nickname), CHAR(1000) CHARACTER SET utf8mb4)          nickname,

执行成功!

MYSQL使用REGEXP实现用户列表首字母检索_第1张图片

 

你可能感兴趣的:(mysql,数据库,database)