Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/82.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用PostgreSQL的查询条件联接_Sql_Postgresql - Fatal编程技术网

使用PostgreSQL的查询条件联接

使用PostgreSQL的查询条件联接,sql,postgresql,Sql,Postgresql,我有一个例子,我需要在每个函数变量的连接中运行不同的查询 目前我的职能是: CREATE OR REPLACE FUNCTION a(type_f boolean) RETURNS SETOF rowtypes AS $$ declare row rowtypes ; begin .... select... from.. left join (select pp.a, avg(ppp.priceusd) as avgpricetf from pp

我有一个例子,我需要在每个函数变量的连接中运行不同的查询

目前我的职能是:

CREATE OR REPLACE FUNCTION a(type_f boolean)
  RETURNS SETOF rowtypes AS
$$
declare row rowtypes ;
begin   
....
select...
from..
left join (select pp.a, avg(ppp.priceusd) as avgpricetf
           from pp
           join p on (p.b=pp.b)
           join (...) as ppp on (pp.c=p.c)
           group by pp.a) tfquery on (tfquery.a=main.a)
....
end;
$$
  LANGUAGE plpgsql VOLATILE
这个很好用

我想修改它,这样当
type_f=True
此查询将在原始查询的join instad中运行时:

left join (select pp.a,p.d, avg(ppp.priceusd) as avgpricetf
           from pp
           join p on (p.b=pp.b)
           join (...) as ppp on (pp.c=p.c)
           group by pp.a,p.d) tfquery on (tfquery.a=main.a and tfquery.d=main.d)
正如您所看到的,查询以及连接本身的条件都发生了更改

基本上

类型f=False时
执行以下操作:

left join (select pp.a, avg(ppp.priceusd) as avgpricetf
           from pp
           join p on (p.b=pp.b)
           join (...) as ppp on (pp.c=p.c)
           group by pp.a) tfquery on (tfquery.a=main.a)
left join (select pp.a,p.d, avg(ppp.priceusd) as avgpricetf
           from pp
           join p on (p.b=pp.b)
           join (...) as ppp on (pp.c=p.c)
           group by pp.a,p.d) tfquery on (tfquery.a=main.a and tfquery.d=main.d)
当:
type\u f=True
do:

left join (select pp.a, avg(ppp.priceusd) as avgpricetf
           from pp
           join p on (p.b=pp.b)
           join (...) as ppp on (pp.c=p.c)
           group by pp.a) tfquery on (tfquery.a=main.a)
left join (select pp.a,p.d, avg(ppp.priceusd) as avgpricetf
           from pp
           join p on (p.b=pp.b)
           join (...) as ppp on (pp.c=p.c)
           group by pp.a,p.d) tfquery on (tfquery.a=main.a and tfquery.d=main.d)

我如何才能做到这一点?

您可以使用这样的逻辑消除查询的所有可能可读性,并获得预期结果:

Select *
from A
left outer join
   ( select * from B where type_f
     union all
     select *, A.field from C where not type_f
   ) X
on X.n = A.n and X.field = A.field
....

但是在在它们之间是不同的。@Tov3,是的,您可以从外部表中附加一个假字段。@Tov3,或者您可以组合一个表达式:
(type\u f and condition1)或(not type\u f and condition2)
在使用UNION时,您不能定义不同的选择类型。所以你不能做
select*from。。。u在选择*时,从
中选择一个字段。此外,我无法将
,p.d
添加到第一个查询的选择中。它不适用于
分组依据
。所以我不明白工会怎么能work@Tov3当然,伙计,你应该选择正确的字段和类型。