3 回答

TA貢獻1906條經驗 獲得超10個贊
如果可能,則無論如何僅存儲數字,應將列的數據類型更改為數字。
如果您無法執行此操作,則將列值integer 強制轉換為
select col from yourtable
order by cast(col as unsigned)
或隱式地使用例如數學運算來強制轉換為數字
select col from yourtable
order by col + 0
BTW MySQL將字符串從左到右轉換。例子:
string value | integer value after conversion
--------------+--------------------------------
'1' | 1
'ABC' | 0 /* the string does not contain a number, so the result is 0 */
'123miles' | 123
'$123' | 0 /* the left side of the string does not start with a number */

TA貢獻1875條經驗 獲得超5個贊
我要排序的列具有字母和數字的任意組合,因此我以本文中的建議為起點,并提出了建議。
DECLARE @tmp TABLE (ID VARCHAR(50));
INSERT INTO @tmp VALUES ('XYZ300');
INSERT INTO @tmp VALUES ('XYZ1002');
INSERT INTO @tmp VALUES ('106');
INSERT INTO @tmp VALUES ('206');
INSERT INTO @tmp VALUES ('1002');
INSERT INTO @tmp VALUES ('J206');
INSERT INTO @tmp VALUES ('J1002');
SELECT ID, (CASE WHEN ISNUMERIC(ID) = 1 THEN 0 ELSE 1 END) IsNum
FROM @tmp
ORDER BY IsNum, LEN(ID), ID;
結果
ID
------------------------
106
206
1002
J206
J1002
XYZ300
XYZ1002
希望這可以幫助

TA貢獻1856條經驗 獲得超5個贊
另一種轉換方式。
如果您有字符串字段,則可以按以下方式對其進行轉換或將其數字部分轉換:添加前導零以使所有整數字符串具有相同的長度。
ORDER BY CONCAT( REPEAT( "0", 18 - LENGTH( stringfield ) ) , stringfield )
或按字段的一部分排序,例如“ tensymbols13”,“ tensymbols1222”等。
ORDER BY CONCAT( REPEAT( "0", 18 - LENGTH( LEFT( stringfield , 10 ) ) ) , LEFT( stringfield , 10 ) )
添加回答
舉報