简体   繁体   中英

Querying a self referencing junction table

I have the master table (Table 1) with fields UI and name

-----------------
UI      name
-----------------
T001    Organism
T002    Plant
T004    Fungus
T005    Virus
T007    Bacterium
-----------------

and second table (Table 2) with name1 and name2 fields

---------------------
name1       name2
---------------------
Organism    Organism
Organism    Fungus
Plant       Virus
Virus       Bacterium
Organism    Bacterium
---------------------

I need to generate the following output

------------
UI1     UI2
------------
T001    T001
T001    T004
T002    T005
T005    T007
T001    T007
------------

Here is my initial attempt

SELECT * FROM table2 AS t2
JOIN table1 AS t1 ON t2.name1 = t1.name
JOIN table1 AS t3 ON t2.name2 = t3.name;

which, unfortunately, returns wrong number of rows. I wonder how to do joins correctly.

One possible way is to use two aliases on table1:

select
    t1a.UI as UI1,
    t1b.UI as UI2
from
    table2 t2,
    table1 t1a,
    table1 t1b
where
    t2.name1 = t1a.name and
    t2.name2 = t1b.name;

You can do it by using subquery in select statement of table2.

Here is the code:

select 
(select UI from table1 t where t.name=t2.name1) AS UI1,
(select UI from table1 t where t.name=t2.name2) AS UI2
from table2 t2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM