MySQL选择列名作为字段 [英] MySQL select column name as field
本文介绍了MySQL选择列名作为字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个看起来像这样的mysql表:
I have a mysql table that looks something like this:
id | col_1 | col_2 | col_3
---|-------|-------|------
1 | 2 | 34 | 64
2 | 6 | 53 | 23
我希望能够查询ID并获取多行,每列一行.例如:
I would like to be able to query on the id and get multiple rows, one for each column. E.g:
SELECT column_name as column, column_value as value FROM my_table WHERE id=1;
哪个会给我的?
column | value
-------|-------
col_1 | 2
col_2 | 34
col_3 | 64
我需要使用什么来制定这样的查询?
What would I need to use to formulate a query like this?
非常感谢
推荐答案
这称为枢轴.实际上,这是一个反向枢纽.有关某些背景,请参见此处. http://www.artfulsoftware.com/infotree/queries.php#78
This is called a pivot. Actually it's a reverse pivot. See here for some background. http://www.artfulsoftware.com/infotree/queries.php#78
MySQL很难做到.脖子很疼.许多在MySQL中从事此类工作的人都使用程序来生成这些查询.
MySQL does it the hard way. It's a pain in the neck. Many people who do lots of this kind of work in MySQL use programs to generate these queries.
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
这篇关于MySQL选择列名作为字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文