我有一个mysql表:
| Col1 | Col2 | Col3 |
++++++++++++++++++++++
| 3.2 | 2 | 1 |
有没有办法获取这样的数据:
| Name | Value |
++++++++++++++++
| Col1 | 3.2 |
| Col2 | 2 |
| Col3 | 1 |
我需要查询,允许我获取列名和值。
答案 0 :(得分:1)
我已根据您的需求调整this answer,并做出以下假设:1)您正在寻找通用解决方案。 2)在我的例子中,表格的名称是单元格。
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'select ''',
c.column_name,
''' as Name, ',
c.column_name,
' as Value
from cells'
) SEPARATOR ' UNION ALL '
) INTO @sql
FROM information_schema.columns c
where c.table_name = 'cells'
order by c.ordinal_position;
SET @sql
= CONCAT('select Name,Value
from
(', @sql, ') x order by Name');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;