项目中有时候需要按照汉字的拼音排序,比如联系人列表、矿物分类等,有的还需要按拼音字母从A到Z分类显示。
如果存储汉字的字段编码使用的是GBK字符集,因为GBK内码编码时本身就采用了拼音排序的方法(常用一级汉字3755个采用拼音排序,二级汉字就不是了,但考虑到人名等都是常用汉字,因此只是针对一级汉字能正确排序也够用了),直接在查询语句后面添加ORDER BY name ASC,查询结果将按照姓氏的升序排序;如果存储姓名的字段采用的是utf8字符集,需要在排序的时候对字段进行转码,对应的代码是ORDER BY convert(name using gbk) ASC,同样,查询的结果也是按照姓氏的升序排序。
按拼音首字母分类显示的时候,需要借助一个中间表,存储的是字母对应的汉字的编码范围,这样的话,每次取出汉字然后跟中间表比对就可以了,中间表创建和插入数据的SQL如下:
/* Navicat MySQL Data Transfer Target Server Type : MYSQL Target Server Version : 50617 File Encoding : 65001 Date: 2015-07-02 11:12:15 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for t_coslers -- ---------------------------- DROP TABLE IF EXISTS `t_coslers`; CREATE TABLE `t_coslers` ( `id` int(11) NOT NULL AUTO_INCREMENT, `f_PY` char(1) CHARACTER SET utf8 DEFAULT NULL, `cBegin` smallint(5) unsigned NOT NULL, `cEnd` smallint(5) unsigned NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=24 DEFAULT CHARSET=latin1; -- ---------------------------- -- Records of t_coslers -- ---------------------------- INSERT INTO `t_coslers` VALUES (\'1\', \'A\', \'45217\', \'45252\'); INSERT INTO `t_coslers` VALUES (\'2\', \'B\', \'45253\', \'45760\'); INSERT INTO `t_coslers` VALUES (\'3\', \'C\', \'45761\', \'46317\'); INSERT INTO `t_coslers` VALUES (\'4\', \'D\', \'46318\', \'46825\'); INSERT INTO `t_coslers` VALUES (\'5\', \'E\', \'46826\', \'47009\'); INSERT INTO `t_coslers` VALUES (\'6\', \'F\', \'47010\', \'47296\'); INSERT INTO `t_coslers` VALUES (\'7\', \'G\', \'47297\', \'47613\'); INSERT INTO `t_coslers` VALUES (\'8\', \'H\', \'47614\', \'48118\'); INSERT INTO `t_coslers` VALUES (\'9\', \'J\', \'48119\', \'49061\'); INSERT INTO `t_coslers` VALUES (\'10\', \'K\', \'49062\', \'49323\'); INSERT INTO `t_coslers` VALUES (\'11\', \'L\', \'49324\', \'49895\'); INSERT INTO `t_coslers` VALUES (\'12\', \'M\', \'49896\', \'50370\'); INSERT INTO `t_coslers` VALUES (\'13\', \'N\', \'50371\', \'50613\'); INSERT INTO `t_coslers` VALUES (\'14\', \'O\', \'50614\', \'50621\'); INSERT INTO `t_coslers` VALUES (\'15\', \'P\', \'50622\', \'50905\'); INSERT INTO `t_coslers` VALUES (\'16\', \'Q\', \'50906\', \'51386\'); INSERT INTO `t_coslers` VALUES (\'17\', \'R\', \'51387\', \'51445\'); INSERT INTO `t_coslers` VALUES (\'18\', \'S\', \'51446\', \'52217\'); INSERT INTO `t_coslers` VALUES (\'19\', \'T\', \'52218\', \'52697\'); INSERT INTO `t_coslers` VALUES (\'20\', \'W\', \'52698\', \'52979\'); INSERT INTO `t_coslers` VALUES (\'21\', \'X\', \'52980\', \'53640\'); INSERT INTO `t_coslers` VALUES (\'22\', \'Y\', \'53689\', \'54480\'); INSERT INTO `t_coslers` VALUES (\'23\', \'Z\', \'54481\', \'55289\');
借助中间表查询汉字首字母的示例SQL如下(utf8字符集):
SELECT t1.id, t1.name, t2.f_PY FROM t_user t1, t_coslers t2 WHERE CONV(HEX(LEFT(CONVERT(t1.name USING gbk ), 1)), 16, 10) BETWEEN t2.cBegin AND t2.cEnd ORDER BY convert(t1.name using gbk) ASC
需要注意的一点是,上述的排序、分类方法对多音字的支持并不是很好,要求高精度的同学慎用。