Im trying to do multiple LEFT JOIN’s on the same column of a table.I need to LEFT JOIN “table2.words” with “table1.color” and “table2.words” with “table1.food”. How do I do this? and can I do it by making the left joined “table2.words” a new column?
My SQL code:
SELECT table1.id, table1.color, table2.words
FROM table1
LEFT JOIN table2 ON table1.color=table2.id
LEFT JOIN table2 ON table1.food=table2.id
table1:
--------------------------------
| id | color | food |
--------------------------------
| 1 | 1 | 3 |
| 2 | 1 | 4 |
| 3 | 1 | 3 |
| 4 | 1 | 4 |
| 5 | 2 | 3 |
| 6 | 2 | 4 |
| 7 | 2 | 3 |
| 8 | 2 | 4 |
--------------------------------
table2:
---------------------------
| id | words |
---------------------------
| 1 | yellow |
| 2 | blue |
| 3 | cookies |
| 4 | milk |
---------------------------
What Im trying to output:
----------------------------------------
| id | colorname | foodname |
----------------------------------------
| 1 | yellow | cookies |
| 2 | yellow | milk |
| 3 | yellow | cookies |
| 4 | yellow | milk |
| 5 | blue | cookies |
| 6 | blue | milk |
| 7 | blue | cookies |
| 8 | blue | milk |
----------------------------------------
Note: I cant change the table structures.
Your Sample Data
Results of My Query
UPDATE 2012-05-14 19:10 EDT
In the event there are values for food or color that do not exist, here is the adjusted query:
I will add rows to table1 and run this new query
Given any invalid data,
LEFT JOINin still needed.