簡體   English   中英

如何從MYSQL中的Varchar字段中選擇最大數字

[英]How to Select Max Numeric from Varchar Field in MYSQL

select userid from user;

+--------+
| userid |
+--------+
| .1.    |
| .1.1.  |
| .2.    |
| .3.    |
| .3.1.  |
| .3.1.1 |
+--------+

在這里,我想從第一個數字中選擇最大數字(即 3)。

select max(userid) as userid from user where userid like ".%.";

+--------+
| userid |
+--------+
| .3.1.  |
+--------+

但是,這不是我想要的。 我想要的輸出是 3 沒有數字兩邊的點。 我想要第四個值

select userid from user;

您可以使用SUBSTRING_INDEX從每個userid字符串中提取第一個數字,然后取其中的MAX

SELECT MAX(CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(userid, '.', 2), '.', -1) AS UNSIGNED)) AS userid
FROM user

請注意,您需要CAST值取整數以確保例如11比種高3

輸出

3

SQLFiddle 上的演示

像這樣的事情,也許:

SELECT   *
FROM     user
ORDER BY SUBSTRING_INDEX(SUBSTRING_INDEX(userid,'.',2),'.',-1) DESC, LENGTH(userid) ASC;
select trim('.' from max(salary))   from TEST_EMPLOYEE  where salary like '._.' ; 
-- O/P 
-- 3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM