首页 > 解决方案 > 如何在 PostgreSQL 中创建一个单词/字符串的所有可能字谜的列表

问题描述

如何在PostgreSQL中创建一个单词/字符串的所有可能字谜的列表。

例如,如果 String 是“ act ”,那么所需的输出应该是:

行动, atc, cta, 猫, tac, tca

我有一个表'tbl_words',其中包含数百万个单词。

然后我想从这个字谜列表中检查/搜索我的数据库表中的有效单词。

就像上面的字谜列表一样,有效的单词是:act, cat

有没有办法做到这一点?

更新1:

我需要这样的输出:(给定单词的所有排列)

在此处输入图像描述

任何想法 ??

标签: sqlpostgresqlanagram

解决方案


查询生成 3 个元素集的所有排列:

with recursive numbers as (
    select generate_series(1, 3) as i
),
rec as (
    select i, array[i] as p
    from numbers
union all
    select n.i, p || n.i
    from numbers n
    join rec on cardinality(p) < 3 and not n.i = any(p)
)
select p as permutation
from rec
where cardinality(p) = 3
order by 1

 permutation 
-------------
 {1,2,3}
 {1,3,2}
 {2,1,3}
 {2,3,1}
 {3,1,2}
 {3,2,1}
(6 rows)

修改最终查询以生成给定单词的字母排列:

with recursive numbers as (
    select generate_series(1, 3) as i
),
rec as (
    select i, array[i] as p
    from numbers
union all
    select n.i, p || n.i
    from numbers n
    join rec on cardinality(p) < 3 and not n.i = any(p)
)
select a[p[1]] || a[p[2]] || a[p[3]] as result
from rec
cross join regexp_split_to_array('act', '') as a
where cardinality(p) = 3
order by 1

 result 
--------
 act
 atc
 cat
 cta
 tac
 tca
(6 rows)    

推荐阅读