Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to left join on 2 fields using the same table

I have the following fiddle :

https://www.db-fiddle.com/f/TSmNDk3rMUtYCi8NNVJND/0

My goal is to left join on two fields but using the same table.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here is my two table structure.

-------------
|    Tab1   |
-------------
| id        |
| group1_id |
| group2_id |
-------------


--------------
| groupTable |
--------------
| id         |
| name       |
--------------

Here is some data for example :

Tab1 :

------------------------------
| id | group1_id | group2_id |
------------------------------
| 1  | 3         | 1         |
| 2  | 3         | 2         |
| 3  | 1         | 3         |
------------------------------

groupTable :

--------------
| id | name  |
--------------
| 1  | cars  |
| 2  | bikes |
| 3  | boats |
--------------

And the expected result :

------------------------
| id | group1 | group2 |
------------------------
| 1  | boats  | cars   |
| 2  | boats  | bikes  |
| 3  | cars   | boats  |
------------------------

My test requests are in the fiddle

>Solution :

Well, the same table can be LEFT JOIN twice.

The query is:

SELECT Tab1.id, g1.name AS group1, g2.name AS group2
FROM Tab1
LEFT JOIN groupTable g1 ON Tab1.group1_id = g1.id
LEFT JOIN groupTable g2 ON Tab1.group2_id = g2.id

The DB Fiddle is updated: https://www.db-fiddle.com/f/TSmNDk3rMUtYCi8NNVJND/1

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading