Strip last two characters of a column in MySQL

匿名 (未验证) 提交于 2019-12-03 01:29:01

问题:

I have an SQL column where the entries are strings. I need to spit out those entries after trimming the last two characters, e.g. if the entry is 199902345 it should output 1999023.

I tried looking into TRIM but looks like it offers trimming only if we know what are the last two characters. But in my case, I don't know what those last two numbers are and they just needs to be discarded.

So, in short, what MySQL string operation enables to trim the last two characters of a string?

I must add that the length of the string is not fixed. It could be 9 character, 11 character or whatsoever.

回答1:

Use the MySQL SUBSTRING function to extract portion of a string. Use CHAR_LENGTH function to calculate the number of characters in the string.

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 


回答2:

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

LEFT(col,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.



回答3:

substring().

http://dev.mysql.com/doc/refman/5.0/en/string-functions.html



回答4:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!