0

如何使用 SQL 确定两个或多个字符串的共享开头?

例如,假设我有 3 个 URI:

'http://www.example.com/service/1'
'http://www.example.com/service/2'
'http://www.example.com/service/3'

如何确定它们都'http:://www.example.com/service/'使用 SQL 共享?

4

2 回答 2

0

您可以在查询中使用 LIKE 关键字。例如:

SELECT column FROM table WHERE column LIKE '[String to match]%'

您只需要知道/输入您要匹配的字符串。在你的情况下:

'http:://www.example.com/service/'
于 2013-08-09T22:03:17.167 回答
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/
于 2013-08-10T12:27:28.107 回答