postgres:将结果查询到变量中,以备后用

时间:2018-11-07 20:17:11

标签: sql postgresql

我有一个复杂的查询,其中某些部分经常会重复。因此,我想将一些子查询的结果存储到变量中,然后可以在主查询中使用该变量。

例如,我想将变量'variable_id'设置为等于SELECT查询,将variable_school_id设置为等于另一个SELECT查询:

variable_id integer := (SELECT id FROM account WHERE email = 'test@test.com');
variable_school_id integer := (SELECT school FROM account WHERE email = 'test@test.com');

然后,我想在看起来像这样的查询中使用这些变量:

select * from doctor where account_id = variable_id AND school = variable_school_id ;

我该怎么做?

1 个答案:

答案 0 :(得分:1)

您不能只使用CTE吗?

with params as (
      SELECT id, school
      FROM account
      WHERE email = 'test@test.com'
     )
select d.*
from params cross join
     doctor d
     on d.account_id = params.id and d.school = params.school;