如何使用SQL确定两个或多个字符串的共享开头?
例如,假设我有3个URI:
'http://www.example.com/service/1'
'http://www.example.com/service/2'
'http://www.example.com/service/3'
如何使用SQL确定它们共享'http:://www.example.com/service/'
?
答案 0 :(得分:0)
您可以在查询中使用LIKE关键字。例如:
SELECT column FROM table WHERE column LIKE '[String to match]%'
你只需要知道/输入你想要匹配的字符串。在你的情况下:
'http:://www.example.com/service/'
答案 1 :(得分:0)
create or replace function string_common_start (s text, t text)
returns text as $$
declare
sa char(1)[] = string_to_array(s, null);
ta char(1)[] = string_to_array(t, null);
output_s text = '';
begin
if s = t or t = '' or s = ''
then return t;
end if;
for i in 1 .. least(length(s), length(t)) loop
if sa[i] = ta[i]
then
output_s = output_s || sa[i];
else
exit;
end if;
end loop;
return output_s;
end; $$ language plpgsql strict;
create aggregate string_common_start (text) (
sfunc = string_common_start,
stype = text
);
它不会聚合空值
select string_common_start(s)
from (values
('http://www.example.com/service/1'),
('http://www.example.com/service/2'),
('http://www.example.com/service/3'),
(null)
) s(s);
string_common_start
---------------------------------
http://www.example.com/service/