数据库最常见的条目查询

时间:2013-05-20 14:52:42

标签: php mysql sql database

得到了帮助显示结果的帮助,它没有显示我需要的结果。

我有这个

表名=权力 列名= power1,power2,power2,power4,power5

 $res = mysql_query("select power1, power2, power2, power4, power5, 
 count(*) as cnt 
 from power 
 group by power1, power2, power2, power4, power5 
 order by cnt desc limit 5;");

显示表格中的特定行,而不仅仅是表格中的5个最常见数字

the table entries

the results

你可以看到,而不是显示前五个数字,这至少应该显示数字1,5& 2,它显示第2行。

任何想法都会受到极大的欢迎。

非常感谢

3 个答案:

答案 0 :(得分:5)

要获取表col中的x列中最常见的5个值:

select col, count(*) as cnt
from x
group by col
order by cnt desc
limit 5;

如果您想要获取五列中的五个最常见的数字(在我的原始答案之后主要更改问题),这里有一种方法:

select power, count(*) as cnt
from (select (case when n = 1 then power1
                   when n = 2 then power2
                   when n = 3 then power3
                   when n = 4 then power4
                   when n = 5 then power5
              end) as power
      from power p cross join
           (select 1 as n union all select 2 union all select 3 union all select 4 union all select 5
           ) n
     ) p

这会将所有列放入单个列中,然后返回最常用的值。

答案 1 :(得分:0)

要获取所有列中前5个最常见的值,您必须加入该表5次

 Select top 5 val From
 (Select power1 val From table
  Union Select power2 val From table
  Union Select power3 val From table
  Union Select power4 val From table
  Union Select power5 val From table) z
 Group By val
 Order By Count(*) Desc

答案 2 :(得分:0)

Select Z.Num, Count(*) As Cnt
From    (
        Select power1 As Num From power
        Union All Select power2 From power
        Union All Select power3 From power
        Union All Select power4 From power
        Union All Select power5 From power
        ) As Z
Group By Z.Num
Order By Count(*) Desc
Limit 5

确保使用Union All,否则您将获得1作为每个离散数字的计数。

SQL Fiddle version