SQL Query多列从同一个表中选择

时间:2015-02-24 20:58:52

标签: sql oracle oracle11g

我正在尝试连接两个表,其中表1从表2中提取值并将它们存储在单独的列中。描述情况:

Table 1
[ID][Name][TBL2_ID_Field1][TBL2_ID_Field2]
 1   XYZ   3               4

Table 2
[ID][Type][Description1][Description2]
 3   AA    TEST          TEST
 4   BB    TEST2         TEST2

我需要表格显示如下内容:

[ID][Name][TBL2_ID_Field1_DESC1][TBL2_ID_Field2_DESC1]
 1   XYZ   TEST                  TEST2

查询为......

SELECT tbl1.id, tbl1.name, tbl2.description1 as "tbl2_id_field1_desc1", tbl2.description1 as "tbl2_id_field2_desc1"
FROM Table1 tbl1, Table2 tbl2
WHERE tbl1.tbl2_id_field1 = table2.id
AND tbl1.tbl2_id_field2 = table2.id

显然不起作用,但我不确定还有什么可以尝试。

任何帮助表示赞赏!如果我没有说清楚,请告诉我。

1 个答案:

答案 0 :(得分:2)

两次加入table2:

SELECT 
  tbl1.id, 
  tbl1.name, 
  tbl21.description1 as "tbl2_id_field1_desc1", 
  tbl22.description1 as "tbl2_id_field2_desc1"
FROM Table1 tbl1
JOIN Table2 tbl21 ON tbl21.id = tbl1.tbl2_id_field1
JOIN Table2 tbl22 ON tbl22.id = tbl1.tbl2_id_field2;