MySQL select column name as field

后端 未结 2 1853
囚心锁ツ
囚心锁ツ 2021-01-05 01:06

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


        
相关标签:
2条回答
  • 2021-01-05 01:20

    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');       
    
    0 讨论(0)
  • 2021-01-05 01:31

    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
    
    0 讨论(0)
提交回复
热议问题