Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 views
in Technique[技术] by (71.8m points)

pivot - MySQL select column name as field

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

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;

Which would give me:

column | value
-------|-------
col_1  | 2
col_2  | 34
col_3  | 64

What would I need to use to formulate a query like this?

Many thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...