What is the correct way of getting data from a MySQL table based on columns from another? Transposing?

StackOverflow https://stackoverflow.com/questions/5082066

  •  04-12-2019
  •  | 
  •  

Pergunta

I have a table like this:

idstable
+--------+-----+-----+-----+-----+-----+
| userid | id1 | id2 | id3 | id4 | id5 |
+--------+-----+-----+-----+-----+-----+
|   1    |  6  |  2  |  52 |  32 |  16 |
+--------+-----+-----+-----+-----+-----+
|   2    |  12 |  5  |  18 |  21 |  5  |
+--------+-----+-----+-----+-----+-----+
|  ...   | ... | ... | ... | ... | ... |

which i want to get the id numbers stored in the columns and get rows from another table with them. The table i wish to get the rows from is:

namestable
+----+----------+
| id |   name   |
+----+----------+
| 6  |   Bruce  |
+----+----------+
| 2  |   Mary   |
+----+----------+
| 52 |   Dick   |
+----+----------+
| 32 |   Bob    |
+----+----------+
| 16 |   Jack   |
+----+----------+
| .. |   ...    |

The result-set i'm im trying to get is something like:

+------+----+-------+
| User | id | name  |
+------+----+-------+
| 1    | 6  | Bruce |
+------+----+-------+
| 1    | 2  | Mary  |
+------+----+-------+
| 1    | 52 | Dick  |
+------+----+-------+
| 1    | 32 | Bob   |
+------+----+-------+
| 1    | 16 | Jack  |
+------+----+-------+

How can i query the idstable with a userid to retrieve the ids associated with it, to then retrieve the correct rows from the namestable? I've read this is called transposing but i've yet to find a concise example.

Any ideas?

Foi útil?

Solução

join

SELECT idstable.id as User, namestable.id as id, namestable.name as name
FROM idstable it
JOIN namestable nt on (nt.id = it.id1 or nt.id = it.id2 ... 3,4,5 like the first two)

Ideally, your idstable wouldn't have 5 columns, but 5 rows per per id.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top