I have two tables. Table_1 has three foreign keys that are coming from the table_2. I need to select all rows from table_2 where ids are equal to the values of val_1, val_2 and val_3 of a specific row from table_1. For example:
SELECT val_1, val_2, val_3 from table_1 WHERE id = 1;
And then using the result of the first query run
SELECT name FROM table_2 WHERE id IN (101, 102, 103);
Is there a way to do it in one query?
table_1
| id | name | val_1 | val_2 | val_3 |
|---|---|---|---|---|
| 1 | item1 | 101 | 102 | 103 |
| 2 | item2 | 104 | 105 | 106 |
table_2
| id | name |
|---|---|
| 101 | sub_item1 |
| 102 | sub_item2 |
| 103 | sub_item3 |
| 104 | sub_item4 |
| 105 | sub_item5 |
| 106 | sub_item6 |
One way to do it is to concatenate
val_1,val_2andval_3in a subquery and useFIND_IN_SET():Or, join the tables:
See the demo.