简体   繁体   中英

How do I perform a SQL JOIN on the same table twice

I an new to the group and this is my first time posting a question.

I have tbl1 that contains 3 columns (id, type, priority). The data looks like this:

id | type | priority
---+------+---------
1  |   1  |  1
2  |   2  |  1
3  |   1  |  2

I have tbl2 that contains all of my references. The data looks like this:

id  | type1 | type2 | type3 | string
----+-------+-------+-------+---------
12  |   9   |   1   |    1  | single
12  |  10   |   1   |    2  | single
12  |   9   |   2   |    1  | carton
13  |   9   |   1   |    1  | low
13  |   9   |   2   |    1  | high
13  |   4   |   1   |    1  | low
14  |   9   |   1   |    1  | red
14  |   2   |   1   |    1  | red
14  |   9   |   2   |    1  | yellow

I want to join tbl2 on tbl1.type = tbl2.type2 where id=12 , type1=9 and type3=1 .

I also want to join tbl2 on tbl1.priority = tbl2.type2 where id=13 , type1=9 and type3=1 .

My resulting table should look like this:

id | type   | priority
---+--------+---------
1  | single | low
2  | carton | low
3  | single | high

Does that make any sense? In essence, there is one reference table, but it needs to be joined over and over for the various columns in table 1. I don't know if it needs to be join, left join, inner left join.

You can just join your table twice:

SELECT 
   tbl1.id, tbl2_t.string, tbl2_p.string
FROM tbl1
LEFT JOIN tbl2 AS tbl2_t ON tbl1.type = tbl2_t.type2 AND 
                               tbl2_t.id=12 AND tbl2_t.type1=9 AND tbl2_t.type3=1
LEFT JOIN tbl2 AS tbl2_p ON tbl1.priority = tbl2_p.type2 AND 
                               tbl2_p.id=13 AND tbl2_p.type1=9 AND tbl2_p.type3=1

Just create a nested join using the following template: (replace text between < > with your table/column names)

SELECT * FROM (

SELECT * FROM <dbo.myTable1> a
LEFT JOIN
        (SELECT * FROM <dbo.myTable2>) b ON a.<type> = b.<type2> WHERE b.<id>=12 AND b.<type1>=9 AND b.<type3>=1

) c  
  LEFT JOIN 
         (SELECT * FROM <dbo.myTable2>) d ON c.<priority> = d.<type2> WHERE c.<id>=13 AND c.<type1>=9 AND c.<type3>=1

You can use tow different table alias

select a.id,  b.string, c.string 
from tbl1 a 
inner  join tbl2 b on a.type = b.type2 
    and b.id =12 
      and b.type1=9 
        and b.type3.=1
inner join tbl2 c on a.type = c.type2 
    and c.id =13 
      and c.type1=9 
        and c.type3.=1

You can use an "or" clause in the join between the two tables so that it's joining when tbl1.type tlb2.type2, but also when tbl1.priority = tbl2.type2 ... like this:

select tbl1.Id, tbl2.string 
from tbl1 inner join tbl2on (tbl1 .type  =tbl2.type1) or (tbl1 .priority = tbl2.type2)
where type1 = 9 and type3 = 1

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