2016-08-10 6 views
1

nameageの列を持つpersonテーブルがあるとします。サブクエリの参照エイリアス

私は、次のSQL生成DSL書いている:

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

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

を、私はこのように、外側のクエリでp1p2にアクセスできるようにしたいと思います

pj.p1.nameのようなものが理想的でしょう。 personの正確な列名がわからない場合、これを達成する方法はありますか?

答えて

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 

A clause of the form USING (a, b, ...) is shorthand for ON left_table.a = right_table.a AND left_table.b = right_table.b .... Also, USING implies that only one of each pair of equivalent columns will be included in the join output, not both.

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

残念ながら、 'ERROR:column reference"の名前は "あいまいです"。 –

+1

@PhilipKamenarsky更新された回答を確認してください –

+0

それだけです!レコードについて知りませんでした、それはそれを解決します。 –

1

エイリアスp1およびp2は、結合条件の対象外です。 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. 
+0

名前/カウントがわからなくてもすべての列を含める方法はありますか?私。 'p1'から' p1_ * 'と' p2'と同じようにすべての列の名前を変更するには? –

+0

私が知っているわけではありません。ごめんなさい。 – sstan

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

スマート、それは悪い考えではない:) – sstan

関連する問題