Get column name dynamically by Specific row value

前端 未结 2 634
长情又很酷
长情又很酷 2020-12-12 07:40

I am struck at writing a query. Here I want to show the column name based on some specific value

For Instance, my table is like this:

id  | fruits            


        
相关标签:
2条回答
  • 2020-12-12 08:06
    set @q= CONCAT('SELECT columns.column_name 
                    from table inner 
                    join information_schema.columns 
                    on columns.table_schema = "dbname" 
                    and columns.table_name = "table" 
                    and ((',
                    (SELECT GROUP_CONCAT(CONCAT('columns.column_name="',column_name,'"',' and table.',column_name,' = "value','"') SEPARATOR ' OR ')
                    FROM INFORMATION_SCHEMA.COLUMNS 
                    WHERE table_name = 'table'),
                    '))');
    prepare query from @q;
    execute query;
    

    This works for sure..

    Phew!

    Fiddle: http://sqlfiddle.com/#!2/9420c/2/2

    PS: Replace table with your table name ,dbname with your db name and value with your value

    0 讨论(0)
  • 2020-12-12 08:24

    As you encrypted your question as much as possible, I can only guess.

    this table smells of a bad design. And it should be like

     col  | value
     col1 | a
     col1 | b
     col2 | d
    

    and so on.

    than you can easily get your col out from value

    0 讨论(0)
提交回复
热议问题