获取mysql条目的列

时间:2010-05-03 12:16:07

标签: sql mysql database

是否有可能获取数据库条目所属列的名称?

也许我有三列,列名为col1,col2和col3。现在我想为每列选择具有最大条目的列,如下所示。

Select name_of_column(max(col1,col2,col3))

我知道我可以通过information_schema.COLUMNS表中的序号位置询问列的名称,但是如何获取表中数据库条目的序号位置?

3 个答案:

答案 0 :(得分:1)

这将显示表格中的列

SHOW COLUMNS FROM 'table';

然后,您必须使用脚本语言迭代结果。

答案 1 :(得分:1)

如果要在纯SQL中实现它,可以使用CASE语句和其他变量:

 SELECT @m := GREATEST(col1, col2), 
 CASE @m 
      WHEN col1 THEN 'col1' 
      WHEN col2 THEN 'col2' 
 END 
 FROM my_table

答案 2 :(得分:1)

你可以这样做:

select
    case true
        when col1 > col2 and col1 > col3 then 'col1'
        when col2 > col1 and col2 > col3 then 'col2'
        when col3 > col1 and col3 > col2 then 'col3'
    end 
from
    mytable

但如果最大值出现在多列中会怎样?