在处理使用Mysql时,数据表采用utf8字符集,使用中发现中文不能直接按照拼音排序
如果数据表tbl的某字段name的字符编码是latin1_swedish_ci
select * from `tbl` order by birary(name) asc ;
如果数据表tbl的某字段name的字符编码是utf8_general_ci
SELECT name FROM `tbl` WHERE 1 ORDER BY CONVERT( name USING gbk ) COLLATE gbk_chinese_ci ASC
===================
$orderby="convert(`group` USING gbk) COLLATE gbk_chinese_ci,displayorder,navid"
最简单的排序方法
最简单的排序方法只需要一条 SQL语句:
select * from musician_ordered order by convert(name using gbk) collate gbk_chinese_ci;
首先,对name字段进行gbk编码,然后,对编码后的内容根据gbk_chinese_ci进行整理排序。
这样得到的结果,英文是排在中文前面的,而且是根据拼音排序的。
DELIMITER $$CREATE FUNCTION `fristPinyin`(P_NAME VARCHAR(255)) RETURNS varchar(255) CHARSET utf8 DETERMINISTICBEGIN DECLARE V_RETURN VARCHAR(255); DECLARE V_BOOL INT DEFAULT 0; DECLARE FIRST_VARCHAR VARCHAR(1); SET FIRST_VARCHAR = left(CONVERT(P_NAME USING gbk),1); SELECT FIRST_VARCHAR REGEXP '[a-zA-Z]' INTO V_BOOL; IF V_BOOL = 1 THEN SET V_RETURN = FIRST_VARCHAR; ELSE SET V_RETURN = ELT(INTERVAL(CONV(HEX(left(CONVERT(P_NAME 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 IF; RETURN V_RETURN;END$$ DELIMITER;
select intermediary_id, intermediary_name, fristPinyin(intermediary_name) as fristPinyin from t_second_agent_intermediary where city_id = 1337 and intermediary_type = 'zj' ORDER BY fristPinyin ;
未经允许请勿转载:程序喵 » 【MySql】支持中文排序的实现方法