Erdinç Taşkın
Erdinç Taşkın

Reputation: 1578

Matching SQL table header value with another table column value

There are 2 Database table like below there Table_1 & Table_2. Table_1 column index is match with id value of table_2. Name values of Table_2 will be column header at result of query.

Table_1
______________________________________________
| date      |city_1 | city_2 | ... | city_100 |
|-----------|-------|-------------------------|
| 20.02.2013|   4   |   34   | ... |   222    |
| 21.02.2013|   3   |   10   | ... |    33    |
|    ...    |  ...  |   ...  | ... |   ...    |
|_____________________________________________|


  Table_2
___________________
|  id   |   name  |
|-------|---------|
|   1   | newyork |
|   2   | london  |
|  ...  |   ...   |
|  100  | istanbul|
|_________________|

Expected result is below

  __________________________________________________________
  |  date     |  newyork   |   london   |  ...  |  istanbul |
  |-----------|------------|------------|-------|-----------|
  | 20.02.2013|     4      |     34     |  ...  |    222    |
  | 21.02.2013|     3      |     10     |  ...  |     33    |
  |   ...     |    ...     |    ...     |  ...  |    ...    |
  |___________|____________|____________|_______|___________| 

What is the SQL query to get result above?

Thanks

Upvotes: 1

Views: 3676

Answers (1)

fthiella
fthiella

Reputation: 49049

You could use a solution like this:

SET @sql = NULL;

SELECT GROUP_CONCAT(COALESCE(CONCAT(COLUMN_NAME, ' as ', Table_2.Name), COLUMN_NAME))
FROM
  INFORMATION_SCHEMA.COLUMNS
  LEFT JOIN Table_2
  ON Table_2.ID = SUBSTRING_INDEX(COLUMN_NAME, '_', -1)
WHERE table_name = 'Table_1' INTO @sql;

SET @sql = CONCAT('SELECT ', @sql, ' FROM Table_1');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

See it here. This code will extract all columns names of Table_1, and will try to join the name of the columns with the IDs in Table_2. If there's a match, I'm returning the name of the column with an alias, like this:

city_1 AS newyour

and using GROUP_CONCAT the variable @sql will contain all the columns like this:

date,city_1 as newyork,city_2 as london,city_100 as istanbul

I'm then concatenating 'SELECT ' + the column names with alias + ' FROM Table_1', and executing the resulting query.

Upvotes: 2

Related Questions