我有主表{表1),其中包含字段UI
和name
-----------------
UI name
-----------------
T001 Organism
T002 Plant
T004 Fungus
T005 Virus
T007 Bacterium
-----------------
带有name1
和name2
字段的和第二个表(表2)
---------------------
name1 name2
---------------------
Organism Organism
Organism Fungus
Plant Virus
Virus Bacterium
Organism Bacterium
---------------------
我需要生成以下输出
------------
UI1 UI2
------------
T001 T001
T001 T004
T002 T005
T005 T007
T001 T007
------------
这是我最初的尝试
SELECT * FROM table2 AS t2
JOIN table1 AS t1 ON t2.name1 = t1.name
JOIN table1 AS t3 ON t2.name2 = t3.name;
不幸的是,返回错误的行数。我想知道如何正确地进行连接。
答案 0 :(得分:1)
一种可能的方法是在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;
答案 1 :(得分:1)
您可以使用table2的select
语句中的子查询来执行此操作。
以下是代码:
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