Sql 最长匹配
在PostgreSQL中获得最长前缀匹配的准确快速查询的最佳方法是什么 是: A.) select * from table where column in (subselect) ; B.) select * from table where strpos(column,column2) = 1 order by length(column2) desc limit 1 ; C.) select * from table where column ~ column2 order by length(column2) desc limit 1Sql 最长匹配,sql,postgresql,pattern-matching,longest-prefix,Sql,Postgresql,Pattern Matching,Longest Prefix,在PostgreSQL中获得最长前缀匹配的准确快速查询的最佳方法是什么 是: A.) select * from table where column in (subselect) ; B.) select * from table where strpos(column,column2) = 1 order by length(column2) desc limit 1 ; C.) select * from table where column ~ column2 ord
我计划在更新中使用。有什么想法吗?我不知道在PostgreSQL中有一个函数可以直接实现这一点。 A将是PostgreSQL 8.4或更高版本中提供的相当优雅的解决方案的关键元素 我假设一个表过滤器包含过滤器字符串:
CREATE TABLE filter (f_id int, string text);
以及要搜索最长匹配的表tbl:
CREATE TABLE tbl(t_id int, col text);
查询
您没有定义从一组同样长的匹配中选择哪个匹配。我从平局中挑选了一个任意的赢家
我计划在更新中使用
引入了PostgreSQL 9.1,因此您可以在UPDATE语句中直接使用它。是否确实要将每一列与同一行中的另一列进行比较?或者在整个表中查找字符串或字符串列表的最长匹配项?请编辑问题以澄清。我没有完全理解您所说的内容,但是的,您是正确的,我想从单独的表中查找字符串/字符串的最长匹配。你能帮我吗
WITH RECURSIVE
f AS (SELECT f_id, string, length(string) AS flen FROM filter)
,t AS (SELECT t_id, col, length(col) AS tlen FROM tbl)
,x AS (
SELECT t.t_id, f.f_id, t.col, f.string
,2 AS match, LEAST(flen, tlen) AS len
FROM t
JOIN f ON left(t.col, 1) = left(f.string, 1)
UNION ALL
SELECT t_id, f_id, col, string, match + 1, len
FROM x
WHERE left(col, match) = left(string, match)
AND match <= len
)
SELECT DISTINCT
f_id
,string
,first_value(col) OVER w AS col
,first_value(t_id) OVER w AS t_id
,(first_value(match) OVER w -1) AS longest_match
FROM x
WINDOW w AS (PARTITION BY f_id ORDER BY match DESC)
ORDER BY 2,1,3,4;