前些天遇到获取标题首字母的问题,数据库数据很多一条条改太费劲了,网上查了下,果然有高人,分享下。
在 mysql 命令窗口中 :
新建数据表,
DROP TABLE IF EXISTS `pinyin`;
CREATE TABLE `pinyin` (
`letter` char(1) NOT NULL,
`chinese` char(1) NOT NULL,
PRIMARY KEY (`letter`)
) ENGINE=MyISAM DEFAULT CHARSET=gbk;
插入数据
INSERT INTO `pinyin` VALUES
('A','驁'),
('B','簿'),
('C','錯'),
('D','鵽'),
('E','樲'),
('F','鰒'),
('G','腂'),
('H','夻'),
('J','攈'),
('K','穒'),
('L','鱳'),
('M','旀'),
('N','桛'),
('O','漚'),
('P','曝'),
('Q','囕'),
('R','鶸'),
('S','蜶'),
('T','籜'),
('W','鶩'),
('X','鑂'),
('Y','韻'),
('Z','咗');
仍在mysql命令窗口中执行
DELIMITER $$
DROP FUNCTION IF EXISTS `PINYIN`$$
CREATE FUNCTION `PINYIN`(str CHAR(255)) RETURNS char(255)
BEGIN
DECLARE hexCode char(4);
DECLARE pinyin varchar(255);
DECLARE firstChar char(1);
DECLARE aChar char(1);
DECLARE pos int;
DECLARE strLength int;
SET pinyin = '';
SET strLength = CHAR_LENGTH(LTRIM(RTRIM(str)));
SET pos = 1;
SET @str = (CONVERT(str USING gbk));
WHILE pos <&#61; strLength DO
SET &#64;aChar &#61; SUBSTRING(&#64;str,pos,1);
SET hexCode &#61; HEX(&#64;aChar);
IF hexCode >&#61; "8140" AND hexCode <&#61; "FEA0" THEN
SELECT letter into firstChar
FROM pinyin
WHERE chinese >&#61; &#64;aChar
LIMIT 1;
ELSE
SET firstChar &#61; &#64;aChar;
END IF;
SET pinyin &#61; CONCAT(pinyin,firstChar);
SET pos &#61; pos &#43; 1;
END WHILE;
RETURN UPPER(pinyin);
END$$
DELIMITER ;
操作前请备份数据库
使用方法&#xff1a;SELECT pinyin(&#39;获取汉字拼音首字母&#39;);
结果为 hqhzpyszm
或者直接执行 update ‘表’ set ‘字段名’ &#61; pinyin(&#39;字段名&#39;);
如果发现有乱码&#xff1a;
修改 my.ini 文件
default-character-set&#61;gbk
共有两处。。
然后修改mysql data目录下的相应数据库的db.opt配置文件
default-character-set&#61;gbk
default-collation&#61;gbk_chinese_ci
重启mysql后 查询测试&#xff0c;如果还是乱码&#xff0c;将上方命令重新执行下。