MySQL按首字母查询
1 DELIMITER $$ 2 3 CREATE 4 /*[DEFINER = { user | CURRENT_USER }]*/ 5 FUNCTION `401_exam`.`GET_FIRST_PINYIN_CHAR`(PARAM VARCHAR(255))RETURNS VARCHAR(2) CHARSET utf8 6 7 BEGIN 8 DECLARE V_RETURN VARCHAR(255); 9 DECLARE V_FIRST_CHAR VARCHAR(2); 10 SET V_FIRST_CHAR = UPPER(LEFT(PARAM,1)); 11 SET V_RETURN = V_FIRST_CHAR; 12 IF LENGTH( V_FIRST_CHAR) <> CHARACTER_LENGTH( V_FIRST_CHAR ) THEN 13 SET V_RETURN = ELT(INTERVAL(CONV(HEX(LEFT(CONVERT(PARAM USING gbk),1)),16,10), 14 0xB0A1,0xB0C5,0xB2C1,0xB4EE,0xB6EA,0xB7A2,0xB8C1,0xB9FE,0xBBF7, 15 0xBFA6,0xC0AC,0xC2E8,0xC4C3,0xC5B6,0xC5BE,0xC6DA,0xC8BB, 16 0xC8F6,0xCBFA,0xCDDA,0xCEF4,0xD1B9,0xD4D1), 17 'A','B','C','D','E','F','G','H','J','K','L','M','N','O','P','Q','R','S','T','W','X','Y','Z'); 18 END IF; 19 RETURN V_RETURN; 20 END$$ 21 22 23 DELIMITER ;
用到的函数:
left(str,length):从左边开始截取字符串
upper:将字符串转为大写
length(str):计算字符串长度,一个汉字算三个字符,一个数字或字母算一个字符
character_length(str):汉字、数字、字母都算一个字符
convert(expr USING encode):不同字符集之间的数据转换
hex(Number or Str):将数字或字符串转换为十六进制
conv(Number, from, to):将数字从原来的进制转换成指定的进制
interval(N,N1,N2,N3,......):将N的值与后面的值列表进行比较
查询SQL:
SELECT a.dev_id,a.dev_name,GET_FIRST_PINYIN_CHAR(a.dev_name) FROM tn_facility a
WHERE GET_FIRST_PINYIN_CHAR(a.dev_name)='c'