在MySQL中,我有一個名為custom_meta的表,我在那里得到的值是
。id meta_value
1 USNEWYORK01
2 USNEWYORK02
3 USNEWYORK03
4 USNEWYORK04
5 USNEWYORK05
6 USNEWYORK06
7 USNEWYORK07
8 USNEWYORK10
9 USNEWYORK14
10 USNEWYORK16
11 USNEWYORK20
12 USNEWYORK21
13 USNEWYORK32
14 USNEWYORK45
15 USNEWYORK56
16 USNEWYORK78
17 USNEWYORK68
18 USNEWYORK69
19 USNEWYORK80
20 USNEWYORK90
21 USNEWYORK99
22 USNEWYORK100
23 USNEWYORK45
24 USNEWYORK101
現在我想獲得數字最高的meta_value。所以在表中,你可以看到最高的一個是USNEWYORK101。所以為了得到它,我做了這樣的查詢
SELECT meta_value from custom_meta ORDER BY meta_value DESC LIMIT 1
但是它總是得到USNEWYORK99。我也嘗試過使用CAST,但這也是不行的。
所以誰能幫助我完成這個任務?任何建議和意見都將是非常值得贊賞的。
謝謝。
謝謝你。
uj5u.com熱心網友回復:
SELECT id,
meta_value。
Cast(Substring(meta_value, 10, Length(meta_value) ) AS UNSIGNED)
FROM custom_meta
ORDER BY 3 DESC
LIMIT 1;
uj5u.com熱心網友回復:
對于較新版本的MySQL,你可以使用REGEXP_SUBSTR()函式,但由于你使用的是5.7,我們可以用一些其他方法。
假設你總是在你的值的開頭有USNEWYORK,你可以去掉它,只留下后面的內容,使用SUBSTRING()函式。然后你需要執行CAST()來將文本轉換為數字值,從而使排序正常進行。
示例資料
create table custom_meta(meta_value varchar(255) 。)
insert into custom_meta(meta_value) values
('USNEWYORK01'),('USNEWYORK02'),('USNEWYORK45') 。 ('USNEWYORK99'),('USNEWYORK101') 。
解決方案
select
meta_value
from
習慣_meta
order by
cast(substring(meta_value, 10) as unsigned) desc
極限1。
輸出
meta_value
USNEWYORK101
uj5u.com熱心網友回復:
像這樣替換并將其鑄成int:
select * from test
order by CAST(REPLACE(meta_value, "USNEWYORK", "" AS SIGNED) desc;
- IF前綴不是固定的,可以是任何東西,并且mysqldb 8.0 。
select * from test
order by CAST(REGEXP_REPLACE(meta_value, '[^0-9]', ') AS SIGNED) desc;
- IF 前綴不是固定的,可以是任何東西,并且mysqldb 5.7。 你可以創建這個函式,說明這里,并像這樣使用它:
select * from test
order by CAST(STRIP_NON_DIGIT(meta_value) AS SIGNED) desc;
uj5u.com熱心網友回復:
對于MySQL 5.7來說,另一種方法是:
select meta_value,
cast(replace
(replace
(replace
(replace
(replace
(替換
(替換
(替換
(替換
(替換
(替換
(替換
(替換
(替換
(替換
(替換
(替換
(替換
(替換
(替換
(替換
(替換
(替換
(替換
(替換
(replace(meta_value,'A',' ')
,'B',')
,'C','')
,'D','')
,'E','')
,'F','')
,'G','')
,'H','')
,'I','')
,'J','')
,'K','')
,'L','')
,'M','')
,'N','')
,'O','')
,'P','')
,'Q','')
,'R','')
,'S','')
,'T','')
,'U','')
,'V','')
,'W','')
,'X','')
,'Y','')
,'Z','')
as UNSIGNED)
as nr
from test
order by nr desc;
演示。https://www.db-fiddle.com/f/7yUJcuMJPncBBnrExKbzYz/38
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/333997.html
標籤:
