使用关联的行检索查找列两次

时间:2015-10-26 09:45:41

标签: sql database oracle

我有两张桌子。 第一个

farmer_id         Farmer_name
   1               Raju
   2               Jay
   3               Ram
   5               Vinay

第二个

farmer_id      registered_farmer_id  Season
  1                  2               2014-15
  3                  5               2015-16

表一是查找农民姓名的查找表。表2有两列,即farmer_id和registered-farmer_id,它们查找同一个表。即表1.我需要的是

Farmer_id    farmer_name    Registered_farmer_id   Registered_farmer_name
  1           Raju                  2                   Jay
  3           Ram                   5                   Vinay

4 个答案:

答案 0 :(得分:2)

SELECT T2.farmer_id, T1.farmer_name, T2.registered_farmer_id, T3.farmer_name
FROM TABLE2 T2 
LEFT JOIN TABLE1 T1
ON T2.farmer_id = T1.farmer_id
LEFT JOIN TABLE1 T3
ON T2.registered_farmer_id = T3.farmer_id;

使用TABLE1表1的名称,TABLE2表2的名称。

答案 1 :(得分:1)

在MS SQL 2005+中,您可以使用CROSS APPLY

SELECT A.farmer_id, A.Farmer_name, B.farmer_id, B.Farmer_name
FROM (
      SELECT T1.farmer_id, T2.Farmer_name, T3.Registered_farmer_id
      FROM Table1 T1
         INNER JOIN Table T2
            ON T1.farmer_id = T2.farmer_id
     ) AS A
CROSS APPLY (
      SELECT farmer_id, Farmer_name
      FROM Table1
      WHERE farmer_id = A.Registered_farmer_id
      ) AS B

在Oracle中,您改为使用INNER JOIN:

SELECT A.farmer_id, A.Farmer_name, B.farmer_id, B.Farmer_name
FROM (
      SELECT T1.farmer_id, T2.Farmer_name, T3.Registered_farmer_id
      FROM Table1 T1
         INNER JOIN Table T2
            ON T1.farmer_id = T2.farmer_id
     ) AS A
INNER JOIN (
      SELECT farmer_id, Farmer_name
      FROM Table1
      ) AS B
WHERE B.farmer_id = A.Registered_farmer_id

答案 2 :(得分:0)

如果从两个不同的数据库表中调用两个表;那么你应该用另一个名称更改第二个表的id并加入两个表。 最后你可以从合并的表中检索。

答案 3 :(得分:0)

假设您的表名为Table1(查找)和Table2

选择t1.NAME fname,t2.NAME rfname     来自表1 t1,表1 t2,表2     其中t1.id = table1.ID和t2.id = table1.ID2 ;