[Database] postgresql intercepts all characters before the last character, such as V1.0.0 from V1.0.0.20230731110947

In PostgreSQL, we can use the position function and split_part function to intercept .all characters before the last one. Both functions are very useful, especially when working with text data.

position function

The position function is used to find the position of a substring in a string. Its syntax is as follows:

POSITION(substring IN string)

Among them, substring is the substring to be found, and string is the string in which to find the substring. If the substring is found, the first matching position is returned; otherwise, 0 is returned.

For example, suppose we have a table named mytable, which has a column named mycolumn with data type text. We want to find .all characters before the last one in each record, we can use the following query:

SELECT position('.' IN mycolumn) - length(mycolumn) + 1 AS new_length
FROM mytable;

This will return a new column new_length, which contains .the length of all characters before the last one in each record.

split_part function

The split_part function is used to split a string into multiple substrings. Its syntax is as follows:

SPLIT_PART(string, delimiter, field)

Among them, string is the string to be split, delimiter is the separator, and field is the position of the substring to be returned. If field is greater than the number of substrings in the string, an empty string is returned.

For example, suppose we want to split each string in mycolumn according to .the order and return .all characters after the last one, we can use the following query:

SELECT split_part(mycolumn, '.', -1) AS new_string
FROM mytable;

This will return a new column new_string containing .all characters after the last one in each record.

Comprehensive use of position and split_part functions

Sometimes we need to use the position and split_part functions together to perform more complex text operations. For example, suppose we want to extract .all characters after the last one from each string in mycolumn, but only the first three characters. The following query can be used:

SELECT substring(mycolumn FROM position('.' IN mycolumn) - length(mycolumn) + 1 FOR 3) AS new_string
FROM mytable;

This will return a new column new_string containing the first .three characters after the last one in each record. Note that the substring function is used here to intercept part of the string.

Guess you like

Origin blog.csdn.net/luansj/article/details/132063779