在 MySQL 中去掉列的最后两个字符

我有一个 SQL 列,其中的条目是字符串。我需要显示这些条目后,修剪最后两个字符,例如,如果条目是 199902345它应该输出 1999023

我试图看进 TRIM,但看起来它提供修剪,只有当我们知道什么是最后两个字符。但在我的情况下,我不知道最后两个数字是什么,它们只是需要被丢弃。

那么,简而言之,什么 MySQL 字符串操作能够修剪字符串的最后两个字符呢?

我必须补充的是,字符串的长度是不固定的。它可以是9个字符,11个字符或任何东西。

141172 次浏览

To select all characters except the last n from a string (or put another way, remove last n characters from a string); use the SUBSTRING and CHAR_LENGTH functions together:

SELECT col
, /* ANSI Syntax  */ SUBSTRING(col FROM 1 FOR CHAR_LENGTH(col) - 2) AS col_trimmed
, /* MySQL Syntax */ SUBSTRING(col,     1,    CHAR_LENGTH(col) - 2) AS col_trimmed
FROM tbl

To remove a specific substring from the end of string, use the TRIM function:

SELECT col
, TRIM(TRAILING '.php' FROM col)
-- index.php becomes index
-- index.php.php becomes index (!)
-- index.txt remains index.txt

You can use a LENGTH(that_string) minus the number of characters you want to remove in the SUBSTRING() select perhaps or use the TRIM() function.

Why not using LEFT(string, length) function instead of substring.

LEFT(col,char_length(col)-2)

you can visit here https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_left to know more about Mysql String Functions.