下面有2个数据库表,Table_1& TABLE_2。 Table_1列索引与table_2的id值匹配。 Table_2的名称值将是查询结果的列标题。
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|
|_________________|
预期结果低于
__________________________________________________________
| date | newyork | london | ... | istanbul |
|-----------|------------|------------|-------|-----------|
| 20.02.2013| 4 | 34 | ... | 222 |
| 21.02.2013| 3 | 10 | ... | 33 |
| ... | ... | ... | ... | ... |
|___________|____________|____________|_______|___________|
获取上述结果的SQL查询是什么?
由于
答案 0 :(得分:2)
你可以使用这样的解决方案:
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;
见here。 此代码将提取Table_1的所有列名称,并尝试使用Table_2中的ID连接列的名称。如果匹配,我将使用别名返回列的名称,如下所示:
city_1 AS newyour
并使用GROUP_CONCAT变量@sql将包含所有列,如下所示:
date,city_1 as newyork,city_2 as london,city_100 as istanbul
然后我将'SELECT '
+列名与别名+ ' FROM Table_1'
连接起来,并执行生成的查询。