0

I'm trying to join two tables where table 1 is pulling values from table 2 and storing them in separate columns. To describe the situation:

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

I need the table to display something like:

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

Querying as...

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

is obviously not working but I'm not sure what else to try.

Any help is appreciated! Please let me know if I haven't clarified enough.

2
  • What error message are you getting? Commented Feb 24, 2015 at 21:01
  • I'm not getting any results since I'm querying using the same table2.id twice for two different fields (which contain different values) Commented Feb 24, 2015 at 21:03

1 Answer 1

2

Join table2 twice:

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;
Sign up to request clarification or add additional context in comments.

3 Comments

I was sort of hoping to avoid joining multiple times since the way Table2 is structured is to store values that I would otherwise have to create a few other tables for... but this does query what I need and presents in the way I need it so +1 for that.
Thanks. As to joining twice: there is no way around this. You want to join two records to each table1 record, so it's two joins.
Ah well, fair enough. Thanks for your help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.