子查询中的引用别名

时间:2016-08-10 15:22:25

标签: sql postgresql join subquery

让我们说person表格中包含nameage列。

我正在编写生成以下SQL的DSL:

select *
  from (select * from person p1 inner join person p2 on p1.name = p2.name) as pj;

现在,我希望能够在外部查询中访问p1p2,如下所示:

select *
  from (select * from person p1 inner join person p2 on p1.name = p2.name) as pj
  where p1.name = 'xxx'; <-- DOESN'T WORK

pj.p1.name这样的东西是理想的。如果我不知道person的确切列名,有没有办法实现这一目标?

3 个答案:

答案 0 :(得分:2)

使用using,然后使用pj.name,或者只使用name

create table person (id serial, name text);
insert into person (name) values ('John'),('Mary');

select *
from (
    select *
    from
        person p1
        inner join
        person p2 using(name)
) r
where name = 'John'
;
 name | id | id 
------+----+----
 John |  1 |  1
  

USING(a,b,...)形式的一个子句是ON left_table.a = right_table.a和left_table.b = right_table.b ....的简写。另外,USING意味着每个只有一个一对等效列将包含在连接输出中,而不是两者。

如果只需要join的一侧:

select *
from (
    select p1.*
    from
        person p1
        inner join
        person p2 using(name)
) r
where name = 'John'
;
 id | name 
----+------
  1 | John

如果需要join两个边,则使用记录:

select (p2).id, (p1).name -- or (p2).*, (p1).*
from (
    select p1, p2
    from
        person p1
        inner join
        person p2 using(name)
) r
where (p1).name = 'John'
;
 id | name 
----+------
  1 | John

答案 1 :(得分:2)

获取额外列为其提供正确的别名

select *
from (select *, 
      p1.name as pjName  --Added Column and use this in where clause 
      from person p1 
      inner join person p2 on p1.name = p2.name) as pj
where pjName = 'xxx';

答案 2 :(得分:1)

别名p1p2不在连接条件的范围内。您只能使用pj别名。您需要做的是在子查询中更明确地说明您选择的列,而不是简单地执行SELECT * ...

类似的东西:

select *
  from (select p1.name, <add other required columns here> -- explicitly select one of the name columns here
          from person p1 
         inner join person p2 
            on p1.name = p2.name) as pj
  where pj.name = 'xxx' -- use pj alias here.