您可以通过 ORDER BY CASE 执行此操作,您可以通过 LEFT(phone_number, 4) 获取 phone_number 的前 4 个字符:
SELECT
phone_number
FROM yourtable
ORDER BY
CASE
/* first group of A prefixes */
WHEN LEFT(phone_number, 4) IN ('0911','other_a','another_a') THEN 1
/* first group of B prefixes */
WHEN LEFT(phone_number, 4) IN ('0905','other_b','another_b') THEN 2
/* second group of A prefixes */
WHEN LEFT(phone_number, 4) IN ('0904','some_a','someother_a') THEN 3
/* second group of B prefixes */
WHEN LEFT(phone_number, 4) IN ('0907','some_b','someother_b') THEN 4
ELSE 5
END ASC,
phone_number ASC
替换IN() 中的其他前缀,其中我有other_a,等等......这样做是匹配前4个字符,如果它们在分配的排序组中,只需应用一个数字来排序.在上面的示例中,所有 0911、other_a、another_a 都将被赋予 1,因此排在 0905、other_b、another_b 和您碰巧分配的下一组 A 之前。
在这些组中,对phone_number 应用常规升序排序。
我想我从您的问题中了解到,您的 A 和 B 前缀比您列出的 4 个要多。如果这不正确,您可以将下面的IN() 子句替换为简单的= '0904',例如。
不幸的是,这种方法可能对索引不太友好。如果性能不能满足您的需求,我建议将前缀作为CHAR(4) 存储在单独的列(带有索引)中,并在ORDER BY 中使用。