Click here to Skip to main content
15,886,857 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have three tables including one reference table(including 2 columns Item_IDs with associated Item_names) and two other tables each having a column named ID1,C1 & ID2,C2.
followings are the tables sample structures:

Reference Table:

| item_id | item_name | .....
|     1      |     name1   | ....
|     2      |     name2   | .....
.
.
Table 1:

|   item_id1   |   C1 |
|   5     | 10   |
.
.
Table 2:

|   item_id2   |   C2 |
|   7     |   10 |
.
.
Now, I want to "JOIN" tables Table1 & Table2 where their C1 & C2 columns are equal.
What I want is, in a row of the result table of the above (JOIN) query, I want to have two additional columns one having the item_name of the ID1 of Table1 and one having the item_name of the ID2 of Table2.
For more clarification, below is a sample of the result table(the table that is made of rows in which C1 & C2 of both tables are equal):

| item_id1 | Item_Name1 | item_id2 | Item_Name2 |
| 1     |     name1       | 2     | name2 |
.
.
I appreciate your helping me with writing a suitable sql query. Thanks in advance.
Posted
Updated 26-Dec-14 3:48am
v3
Comments
ZurdoDev 26-Dec-14 8:59am    
I don't follow. ID1 1 is not in your sample data. ID2 2 is also not in your sample data.
Member 11033015 26-Dec-14 9:31am    
Sorry for the mistake..I can't edit the question...consider both "ID1" & "ID2" "item_id".
ZurdoDev 26-Dec-14 9:42am    
You should be able to click Improve question.

I guess I'm still confused as to how you are getting the result. You want "name1" and "name2" in the same row as separate columns but they are separate rows in your reference table. I also don't see how Table1 and Table 2 related to reference table.
Member 11033015 26-Dec-14 9:52am    
Please re-check the updated column names.
Yes,what you mentioned is exactly what I want...
Table1 `item_id1` column includes numbers(IDs) whose values can be found using reference table.
Table2 `item_id2` column includes numbers(IDs) whose values can be found again using reference table.

1 solution

There is really nothing complicated about it. Join the two tables on C1 & C2 columns. Then join twice to Reference Table to retrieve the item name for each item id. And voila:
SQL
select 
  t1.item_id1, ref1.item_name as item_name1, 
  t2.item_id2, ref2.item_name as item_name2
from 
  table1 t1 inner join table2 t2 on t2.C2 = t1.C1
  inner join ReferenceTable ref1 on ref1.item_id = t1.item_id1
  inner join ReferenceTable ref2 on ref2.item_id = t2.item_id2
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900