2016-12-28 54 views
1
Table A 

id name keywords 
1 Obj1 a,b,c,austin black 
2 Obj2 e,f,austin black,h 
3 Obj3 k,l,m,n 
4 Obj4 austin black,t,u,s 
5 Obj5 z,r,q,w 

我需要获取那些包含相似类型关键字的记录。因此,对于表中的结果必须是:Postgresql:获取具有相似列值的记录

Records: 
1,2,4 

由于记录1,2,4是其一个或一些其他关键字匹配与至少任何其他关键字。

+2

正如其他人可能会发表评论,你为什么要存储非标准化CSV格式的关键字数据? –

+0

@TimBiegeleisen是的,我知道这一点。但需要将其存储为其他一些依赖项。对于上面的问题,我想到将一个函数写入数据库本身,它会遍历每个关键字并与其他关键字匹配。但这不是一个有效的解决方案。试图通过解决关键字列来解决任何疑问 –

回答

2

您可以转换“CSV”到一个数组,然后使用Postgres的阵列功能:

select * 
from the_table t1 
where exists (select * 
       from the_table t2 
       where string_to_array(t1.keywords, ',') && string_to_array(t2.keywords, ',') 
       and t1.id <> t2.id); 
相关问题