2017-02-05 8 views
1

これは動物公園の例です。SQL INNER JOIN派生テーブルを使用したサブクエリ

employee、animal、animal_employeeの3つのテーブルがあります。これらのテーブルの間には、n:mテーブルがあります。 私は同じ動物を扱う従業員に問い合わせたいと思う。しかし私がやっているやり方では、私はID番号だけを出力することができます。私は、テーブルにある実際の名前を出力したい:従業員と動物。

これは私が今のところ持っているものです:FROM句の

select distinct a.animal, a.employee, b.employee 
from animal_employee a, animal_employee b 
where a.animal = b.animal and a.employee > b.employee 
+0

テーブルスキーマを転記します。 – McNets

答えて

0

まず、決して使用コンマ。 常には、適切で明示的なJOIN構文を使用します。

私はCTEでこれを行うと思う:

with ae as (
     select ae.*, e.name as employee_name, a.name as animal_name 
     from animal_employee ae join 
      employee e 
      on ae.employee = e.?? join -- don't know what is used for the `JOIN` here 
      animal a 
      on ae.animal = a.??   -- don't know what is used for the `JOIN` here 
    ) 
select a1.animal_name, ae1.employee_name, ae2.employee_name 
from ae ae1 join 
    ae ae2 
    on ae1.animal = ae2.animal and ae1.employee < ae2.employee; 

あなたの質問はテーブル構造については不明です。 ??は、結合に使用される列のためのものです。

結果セットに重複がある場合は、select distinctが必要です。これは、テーブルに重複があった場合にのみ発生します(これは起こりそうもありません)。

+0

が動作しているようですが、ありがとうございます! –

+0

ちょっとした修正を分かち合うために覚えています。 "e.name as animal_name"では "a.name"です。とにかく、もう一度大変感謝しています。 –

+0

@FilipeBreda。 。 。ありがとうございました。 –

関連する問題