📅  最后修改于: 2023-12-03 15:18:38.572000             🧑  作者: Mango
在 PostgreSQL 中,位置函数可以用来确定字符串中子字符串的位置。本文将介绍以下位置函数:
position(substring in string)
: 返回子字符串在字符串中第一次出现的位置(从 1 开始计数),如果子字符串不存在则返回 0。strlen(string)
: 返回字符串中字符的数量(即字符串长度,包括空格)。substring(string, from [, to])
: 返回字符串中从指定位置开始到指定位置结束的子字符串,如果省略 to 参数,则返回从指定位置开始到字符串末尾的子字符串。position(substring in string)
substring
: 要查找的子字符串。string
: 要在其中查找子字符串的字符串。SELECT position('world' in 'hello world'); -- Output: 6
SELECT position('o' in 'hello world'); -- Output: 5
SELECT position('x' in 'hello world'); -- Output: 0
strlen(string)
string
: 要计算长度的字符串。SELECT strlen('hello world'); -- Output: 11
SELECT strlen(''); -- Output: 0
substring(string, from [, to])
string
: 要截取子字符串的字符串。from
: 子字符串的起始位置。to
(可选): 子字符串的结束位置。如果省略该参数,则返回从 from
位置到字符串末尾的子字符串。SELECT substring('hello world', 6, 10); -- Output: ' world'
SELECT substring('hello world', 2); -- Output: 'ello world'
SELECT substring('hello world', 200); -- Output: ''
以上是 PostgreSQL 中位置函数的介绍。它们对于在字符串中查找和截取子字符串非常有用。