我有一个mysql表,看起来像这样:
id | col_1 | col_2 | col_3
---|-------|-------|------
1 | 2 | 34 | 64
2 | 6 | 53 | 23
Run Code Online (Sandbox Code Playgroud)
我希望能够查询id并获取多行,每列一行.例如:
SELECT column_name as column, column_value as value FROM my_table WHERE id=1;
Run Code Online (Sandbox Code Playgroud)
哪个会给我:
column | value
-------|-------
col_1 | 2
col_2 | 34
col_3 | 64
Run Code Online (Sandbox Code Playgroud)
我需要用什么来制定这样的查询?
非常感谢
这称为枢轴.实际上它是一个反向支点.在这里查看一些背景信息.http://www.artfulsoftware.com/infotree/queries.php#78
MySQL很难做到这一点.这是颈部疼痛.许多在MySQL中进行大量此类工作的人使用程序来生成这些查询.
SELECT `column`, column_value
FROM (
SELECT id, 'col_1' as `column`, col_1 as column_value FROM tab
UNION
SELECT id, 'col_2' as `column`, col_2 as column_value FROM tab
UNION
SELECT id, 'col_3' as `column`, col_3 as column_value FROM tab
) pivot
WHERE id=1
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16791 次 |
| 最近记录: |