0

I've been searching for an answer to this for a while and am just not successful. Sorry if this is a duplicate.

I have two tables:

table1
------------------------
|    id    |   name    |
------------------------
|    c1    |   name1   |
|    c2    |   name2   |
|    c3    |   name3   |
|    c4    |   name4   |
------------------------

table2
------------------------------------------------
|    id    |    c1     |    c2     |    c3     |
------------------------------------------------
|     1    |   data11  |   data21  |   data31  |
|     2    |   data12  |   data22  |   data32  |
------------------------------------------------

I need data from the second table, renaming the columns with the contents of the first table like this. The number of columns might not match.

result
------------------------------------
|    id    |   name1   |  name3    |
------------------------------------
|     1    |   data11  |  data31   |
|     2    |   data12  |  data32   |
------------------------------------

[Edit] I am selecting data from the second table like this: "SELECT c1,c3 FROM table2 WHERE id ..." so I don't "know" the names when I do the select.

First I was thinking it would be a simple JOIN, but obviously it's not. I'm kind of stuck right now wondering how to approach this. Thanks

Esprit1st
  • 111
  • 1
  • 6
  • 1
    Does this answer your question? [Setting column values as column names in the SQL query result](https://stackoverflow.com/questions/12808189/setting-column-values-as-column-names-in-the-sql-query-result) – Martin Mar 10 '21 at 18:20
  • Not really, since they are in two completely separate tables. I'm working in PHP and MySQL. I am getting the data out of table two with a simple "SELECT name1,name3 FROM table2 WHERE id ...". I looked into things that I don't really understand like aggregate functions which I don't think work. – Esprit1st Mar 10 '21 at 18:25
  • Consider handling issues of data display in application code – Strawberry Mar 10 '21 at 20:04
  • Can't be done with pure SQL. You need to write a procedure which formats a query string and uses a prepared statement to then execute it. [Find out more](https://dev.mysql.com/doc/refman/8.0/en/sql-prepared-statements.html) – APC Mar 13 '21 at 22:51
  • 1
    Thanks @APC I'll look into that. Good to hear I'm not just missing something simple. – Esprit1st Mar 14 '21 at 00:34

0 Answers0