正则表达式varchar的mysql命令无法正常工作

时间:2019-06-25 14:43:24

标签: mysql regex

我正在尝试通过(varchar字段)查询进行简单排序

我当前的实现是:

SELECT id,name
FROM customer 
ORDER BY IF(name RLIKE '^[a-z]', 1, 2), name 

CREATE TABLE `customer` (
    `id` BIGINT(20) NOT NULL AUTO_INCREMENT,
    `name` VARCHAR(50) NULL DEFAULT NULL,
    PRIMARY KEY (`id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
;

当我向他们订购DESC时,我希望列表相同(颠倒),但实际上不是。例如,该“ 555555555”名称位于ASC的底部,而几乎位于DESC的底部

如果我订购ASC,结果为:

"id"    "name"
"147"   "AAAAAAA 55555"
"86"    "BBB"
"71"    "Building"
"148"   "Building 2"
"150"   "Corporation build"
"142"   "Customer 10.03.17"
"116"   "Customer new"
"131"   "Customer without templates"
"104"   "CustomerTEST"
"117"   "Customer_55 at moment"
"33"    "Ex_Name1414 project Support"
"139"   "FFF"
"126"   "GEARY Project"
"133"   "MMMMM1-1"
"127"   "NEW 14"
"134"   "NIKOI"
"135"   "nnn"
"144"   "NNN"
"138"   "NNNmmm111"
"91"    "Project 1818"
"105"   "Project GO"
"124"   "Project ZIP"
"128"   "SAN FRANCISCO Project"
"182"   "test"
"181"   "test"
"149"   "TEST 9/6"
"115"   "TEST Customer"
"178"   "test2"
"180"   "testing"
"120"   "TESTOVI"
"145"   "vvv"
"121"   "VVVV dnes22"
"132"   "VVVVV Project"
"130"   "Without Template"
"152"   " CATEST CONST "
"156"   " MOUNT CONST"
"154"   " RUDOH CONST "
"153"   " TEST CONST "
"146"   "555555555"

当我尝试订购DESC时,结果不一样(相反) 实际结果是:

"id"    "name"
"130"   "Without Template"
"132"   "VVVVV Project"
"121"   "VVVV dnes22"
"145"   "vvv"
"120"   "TESTOVI"
"180"   "testing"
"178"   "test2"
"115"   "TEST Customer"
"149"   "TEST 9/6"
"182"   "test"
"181"   "test"
"128"   "SAN FRANCISCO Project"
"124"   "Project ZIP"
"105"   "Project GO"
"91"    "Project 1818"
"138"   "NNNmmm111"
"144"   "NNN"
"135"   "nnn"
"134"   "NIKOI"
"127"   "NEW 14"
"133"   "MMMMM1-1"
"126"   "GEARY Project"
"139"   "FFF"
"33"    "Ex_Name1414 project Support"
"117"   "Customer_55 at moment"
"104"   "CustomerTEST"
"131"   "Customer without templates"
"116"   "Customer new"
"142"   "Customer 10.03.17"
"150"   "Corporation build"
"148"   "Building 2"
"71"    "Building"
"86"    "BBB"
"147"   "AAAAAAA 55555"
"146"   "555555555"
"153"   " TEST CONST  "
"154"   " RUDOH CONST  "
"156"   " MOUNT CONST"
"152"   " CATEST CONST "

1 个答案:

答案 0 :(得分:1)

您似乎只更改了name值的顺序,但没有更改组(1或2)的顺序。如果要完全翻转列表,则必须在两个订单部分(条件和列DESC)上使用name使用以下查询:

SELECT id, name
FROM customer 
ORDER BY IF(name RLIKE '^[a-z]', 1, 2) DESC, name DESC

您当前正在使用以下查询:

SELECT id, name
FROM customer 
ORDER BY IF(name RLIKE '^[a-z]', 1, 2), name DESC

-- same as
SELECT id, name
FROM customer 
ORDER BY IF(name RLIKE '^[a-z]', 1, 2) ASC, name DESC

在这种情况下,组的顺序为ASC,而名称的顺序为DESC