如地域表信息:
如果我们想根据NAME 字段 的值, 按照中文拼音首字母排序 :
sql
SELECT CODE, NAME
FROM district_info
ORDER BY CONVERT(name USING gbk) COLLATE gbk_chinese_ci ASC
效果很OK:
那么如果我要整成想电话簿那样, A 分组 B 分组 C 分组呢 ??
方案一
在存储表的时候,直接给新增一个列字段 ,先预习存好首字母
比如:
然后根据首字母分组排序啥的都非常简单了:
SELECT * FROM test
GROUP BY NAME ORDER BY first_alp
效果:
如果我们不能随便改表加字段呢?
方案二
新增一张字母表
CREATE TABLE `alphabet` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` CHAR(1) NULL DEFAULT NULL COLLATE 'utf8_general_ci',
`begin` SMALLINT(5) UNSIGNED NOT NULL,
`end` SMALLINT(5) UNSIGNED NOT NULL,
PRIMARY KEY (`id`) USING BTREE
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
AUTO_INCREMENT=24
;
插入24个字母的默认数据
INSERT INTO `alphabet` VALUES ('1', 'A', '45217', '45252');
INSERT INTO `alphabet` VALUES ('2', 'B', '45253', '45760');
INSERT INTO `alphabet` VALUES ('3', 'C', '45761', '46317');
INSERT INTO `alphabet` VALUES ('4', 'D', '46318', '46825');
INSERT INTO `alphabet` VALUES ('5', 'E', '46826', '47009');
INSERT INTO `alphabet` VALUES ('6', 'F', '47010', '47296');
INSERT INTO `alphabet` VALUES ('7', 'G', '47297', '47613');
INSERT INTO `alphabet` VALUES ('8', 'H', '47614', '48118');
INSERT INTO `alphabet` VALUES ('9', 'J', '48119', '49061');
INSERT INTO `alphabet` VALUES ('10', 'K', '49062', '49323');
INSERT INTO `alphabet` VALUES ('11', 'L', '49324', '49895');
INSERT INTO `alphabet` VALUES ('12', 'M', '49896', '50370');
INSERT INTO `alphabet` VALUES ('13', 'N', '50371', '50613');
INSERT INTO `alphabet` VALUES ('14', 'O', '50614', '50621');
INSERT INTO `alphabet` VALUES ('15', 'P', '50622', '50905');
INSERT INTO `alphabet` VALUES ('16', 'Q', '50906', '51386');
INSERT INTO `alphabet` VALUES ('17', 'R', '51387', '51445');
INSERT INTO `alphabet` VALUES ('18', 'S', '51446', '52217');
INSERT INTO `alphabet` VALUES ('19', 'T', '52218', '52697');
INSERT INTO `alphabet` VALUES ('20', 'W', '52698', '52979');
INSERT INTO `alphabet` VALUES ('21', 'X', '52980', '53640');
INSERT INTO `alphabet` VALUES ('22', 'Y', '53689', '54480');
INSERT INTO `alphabet` VALUES ('23', 'Z', '54481', '55289');
表:
数据:
然后回到我们一开始的例子,地域表的数据,想根据 名称 首字母排序 而且 分组 :
sql :
ps : 大家用的时候 依葫芦画瓢把相关需要 排序的主表字段名、列名换一下就行。 这里拿地域表做示例,根据district_info 地域表的name字段做排序。
SELECT district_info.* , alphabet.name AS first_alp
FROM district_info , alphabet
WHERE CONV(HEX(LEFT(CONVERT(district_info.name USING gbk ), 1)), 16, 10)
BETWEEN alphabet.begin AND alphabet.endORDER BY convert(district_info.name using gbk) ASC
效果,很OK:
好了该篇就到这。