mysql按首字母排序
时间: 2023-08-28 12:20:36 浏览: 99
在MySQL中,要按首字母进行排序,可以使用COLLATE关键字和自定义排序函数来实现。在表的创建语句中,可以使用COLLATE算法对字符进行排序。例如,可以在ORDER BY子句中使用COLLATE语句来按首字母排序。可以使用存储过程来实现这个函数,具体代码如下:
DELIMITER $$
CREATE FUNCTION `fristPinyin`(P_NAME VARCHAR(255)) RETURNS varchar(255) CHARSET utf8 DETERMINISTIC
BEGIN
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语句的ORDER BY子句中调用它,以按照首字母进行排序。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [mysql按首字母排序](https://blog.csdn.net/qq_36944770/article/details/78341192)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [MySQL排序(根据中文首字母排序)](https://blog.csdn.net/qq_41988504/article/details/89014873)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文