Syed Asad Abbas Zaidi
Syed Asad Abbas Zaidi

Reputation: 1066

Postgresql: Get records having similar column values

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

I need to get those records which contains similar type of keywords. Hence the result for the table needs to be:

Records:
1,2,4

Since records 1,2,4 are the one whose some or the other keyword match with at least any other keyword.

Upvotes: 1

Views: 1099

Answers (1)

user330315
user330315

Reputation:

You can convert the "csv" to an array and then use Postgres' array functions:

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);

Upvotes: 2

Related Questions