比如现在有如下表
id   com1   com2   com3   com4
1      4      2      5      82      2      1      6      53      3      3      3      2想根据id的值来检索最大的几列。
比如根据id = 1 检索最大的三列的名字 结果应该是  com1  com3  com4请问有这种sql方法吗?

解决方案 »

  1.   

    select * from 
    (
    select id ,com1 as v ,'com1' as c from 如下表 where id=1
    union all
    select id ,com2 as v ,'com2' as c from 如下表 where id=1
    union all
    select id ,com3 as v ,'com3' as c from 如下表 where id=1
    union all
    select id ,com4 as v ,'com4' as c from 如下表 where id=1
    ) t
    order by v desc
    limit 3;
      

  2.   


    是。如果知道表名,则你可以通过程序来得到列名。
    SELECT * FROM information_schema.`COLUMNS` C;
    你可以通过这个表得到列名。