2017-05-19 26 views
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%' 
... 

上面只是我嘗試運行的PostgreSQL查詢的一個示例。它是兩個完全相似的查詢的聯合。他們僅使用不同的值來匹配string1string2PostgreSQL:傳遞來自數組的值並執行聯合

我有大約20個這樣的查詢,我想做一個聯合。他們只能通過我想使用作爲string1

比較這樣的變量不同,怎樣才能用值['string1', 'string2', 'string3', .., 'string20']這樣的陣列,從這個陣列和工會它們運行在每個變量的查詢?

回答

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

怎麼樣老式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']); 
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||'%')