Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL select column name as field

Tags:

mysql

pivot

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

like image 503
Thomas Clayson Avatar asked Sep 06 '12 11:09

Thomas Clayson


People also ask

How do I select only column names in MySQL?

Get column names from a table using DESC. We can also use the DESC keyword to get the column names.

Can We Use column name as key in MySQL?

To select a column that is also a keyword in MySQL, you need to use backticks around the column name. As you know select is a keyword in MySQL, consider column name as select when creating a new table.

How do I select only column names in SQL?

To get the column name of a table we use sp_help with the name of the object or table name. sp_columns returns all the column names of the object. The following query will return the table's column names: sp_columns @table_name = 'News'

How do I select a column name with a space in MySQL?

To select a column name with spaces, use the back tick symbol with column name. The symbol is ( ` `). Back tick is displayed in the keyboard below the tilde operator ( ~).


2 Answers

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
like image 169
O. Jones Avatar answered Sep 29 '22 12:09

O. Jones


You could do it like this, this will return to you 2 comma separated first one of columns second of values, which you can explode and merge into KEY/VALUE arrays in PHP.

SELECT 
    GROUP_CONCAT(COLUMN_NAME) AS _columns,
    (SELECT 
            GROUP_CONCAT(columnName, ',', columnName)
        FROM table_name
        WHERE id = 1)
FROM
    information_schema.columns
WHERE
    table_name = 'table_name'
        AND COLUMN_NAME IN ('columnName' , 'columnName');       
like image 25
Kao Avatar answered Sep 29 '22 10:09

Kao