我正在尝试在postgreSQL中获取URL中的字符:
www.abc.com/hello/xyz
www.abc.com/hi/pqr
www.abc.com/yellow/xyz
我想要获取:
hello
hi
yellow
目前为止,这是我的代码:
select distinct substring(url, position('/' in url)+ 1) theURL from table;
我只能获取第一个“/”符号
我不确定如何获取第二个符号的位置
我正在尝试在postgreSQL中获取URL中的字符:
www.abc.com/hello/xyz
www.abc.com/hi/pqr
www.abc.com/yellow/xyz
我想要获取:
hello
hi
yellow
目前为止,这是我的代码:
select distinct substring(url, position('/' in url)+ 1) theURL from table;
我只能获取第一个“/”符号
我不确定如何获取第二个符号的位置
regexp_split_to_array()
函数:select (regexp_split_to_array(url, '/'::text))[2]
select split_part(url, '/', 2)
根据您提供的子字符串方法,利用第一个子字符串结果来进行第二次搜索:
select distinct substring(
substring(url, position('/' in url)+ 1)
, 0
, position('/' in substring(url, position('/' in url)+ 1))) AS theURL
from table;
本质上,这个查询使用了你从substring
得到的原始结果来启动下一个\ 的搜索,因此它能够保留第一个和第二个\之间的文本。
如果按字母顺序排序很重要,你可以添加一个外部查询:
SELECT theURL FROM (
select distinct substring(
substring(url, position('/' in url)+ 1)
, 0
, position('/' in substring(url, position('/' in url)+ 1))) AS theURL
from table
) AS xt
ORDER BY xt.theURL;
以下查询甚至适用于像www.abc.com/hello
这样的输入。
SELECT DISTINCT (regexp_matches(url, '/([^/]+)'))[1] theURL
FROM table;
同时它也会跳过空条目
split_part(url, '/', 2)
是最快的方法。原文链接为:https://stackoverflow.com/questions/25272196/how-to-get-substring-from-a-sql-table/25272243#25272243 - Neil McGuigan