sqlpostgresqlsql-in

Select rows according to another table with a comma-separated list of items


Have a table test.

select b from test

b is a text column and contains Apartment,Residential

The other table is a parcel table with a classification column. I'd like to use test.b to select the right classifications in the parcels table.

select * from classi where classification in(select b from test)

this returns no rows

select * from classi where classification =any(select '{'||b||'}' from test)

same story with this one

I may make a function to loop through the b column but I'm trying to find an easier solution

Test case:

create table classi as
select 'Residential'::text as classification 
union
select 'Apartment'::text as classification 
union
select 'Commercial'::text as classification;

create table test as
select 'Apartment,Residential'::text as b;

Solution

  • You need to first split b into an array and then get the rows. A couple of alternatives:

    select * from nj.parcels p where classification = any(select unnest(string_to_array(b, ',')) from test)
    
    select p.* from nj.parcels p 
    INNER JOIN (select unnest(string_to_array(b, ',')) from test) t(classification) ON t.classification = p.classification;
    

    Essential to both is the unnest surrounding string_to_array.