PostgreSQL:传递数组中的值并进行联合

时间:2017-05-19 01:17:41

标签: postgresql

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查询的一个例子。它是两个完全相似的查询的联合。它们仅使用不同的值来匹配string1string2

我有大约20个这样的查询,我想要联合。它们仅因我想用于比较的变量而不同,例如string1

如何使用此类数组['string1', 'string2', 'string3', .., 'string20'],对此数组中的每个变量运行查询并将它们联合起来?

3 个答案:

答案 0 :(得分:1)

老式applicationDidFinishLaunching怎么样?

plpgsql

答案 1 :(得分: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;

答案 2 :(得分: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||'%')