Get column name dynamically by Specific row value

前端 未结 2 668
长情又很酷
长情又很酷 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

提交回复
热议问题