0
WITH temp AS (select * from t1 where c1 = 'string1')
select 'string1' as col1, t2.col2, temp.col3 from t2 inner join temp on t2.c2 = temp.c2 where t2.some_col like 'string1%'
union
WITH temp AS (select * from t1 where c1 = 'string2')
select 'string2' as col1, t2.col2, temp.col3 from t2 inner join temp on t2.c2 = temp.c2 where t2.some_col like 'string2%'
...

Above is just an example of a PostgreSQL query I am trying to run. It's a union of two completely similar queries. They only use different values for matching string1 and string2.

I have about 20 such queries that I want to do a union on. They only differ by the variable I want to use for comparison such as string1

How can I use such array of values ['string1', 'string2', 'string3', .., 'string20'], run a query on each variable from this array and union them?

3 Answers 3

1

What about a old fashioned plpgsql?

CREATE OR REPLACE FUNCTION get_all_foo(arr varchar[]) RETURNS TABLE (col1 TEXT, col2 TEXT, col3 TEXT) AS
$BODY$
DECLARE
   arr_value varchar;
   generated_query varchar := '';
   array_index smallint := 1;
   array_length smallint;
BEGIN
        array_length := array_length(arr, 1);        
        FOREACH arr_value IN ARRAY arr LOOP

                generated_query := generated_query || format(' (WITH temp AS (select * from t1 where c1 = %L) '
                   'select %L as col1, t2.col2, temp.col3 from t2 inner join temp on t2.c2 = temp.c2 where t2.some_col like ''%s%%'')', arr_value, arr_value, arr_value);

                IF array_index < array_length THEN
                        generated_query := generated_query || ' UNION ';
                END IF;

                array_index := array_index+1;

        END LOOP;

        RAISE DEBUG 'Generated query: %', generated_query;

        RETURN QUERY EXECUTE generated_query;

END
$BODY$
LANGUAGE plpgsql;

--Uncomment to see generated query
--SET client_min_messages = DEBUG;
SELECT * FROM get_all_foo(array['string1', 'string2', 'string3', 'string4', 'string5']);
Sign up to request clarification or add additional context in comments.

Comments

0
select c1 as col1, t2.col2, temp.col3 
from 
(select col2, c2 from t2 where 
some_col like 'string1%' or some_col like 'string2%' or <other strings in the similar fashion>) t2 
inner join
(select c1,c2,col3 from t1 where c1 in ('string1', 'string2', <other strings in the similar fashion>)) temp 
 on t2.c2 = temp.c2;

Comments

0
WITH temp AS (
  select *
  from t1
  where c1 = any(array['string1','string2','string3']))
select distinct
  temp.c1 as col1, t2.col2, temp.col3
from t2 inner join
  temp on (t2.c2 = temp.c2 and t2.some_col like temp.c1||'%')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.