如何按频繁值对“GROUP BY”查询结果进行排序?

时间:2016-12-07 09:36:06

标签: php mysql group-by

我写php应用程序,它得到用户浏览器的名称:

+----------+------------+
| name     | browser    |
+----------+------------+
| Puffball | firefox    |
| Chirpy   | edge       |
| Whistler | chrome     |
| Slim     | firefox    |
| Claws    | edge       |
| Fluffy   | chrome     |
| Fang     | chrome     |
| Bowser   | safari     |
| Buffy    | chrome     |
+----------+------------+

我使用这个sql查询来获得带有“GROUP BY”的浏览器,结果是:

$sql = "SELECT * FROM views WHERE linkid = '$string' GROUP BY browser";

array (size=4)
  0 => string 'firefox (length=7)
  1 => string 'edge' (length=4)
  2 => string 'chrome' (length=6)
  3 => string 'safari' (length=6)

我想通过Frequent值对此结果进行排序,如下所示:

array (size=4)
  0 => string 'chrome (length=6)
  1 => string 'edge' (length=4)
  2 => string 'firefox' (length=7)
  3 => string 'safari' (length=6)

坦!

2 个答案:

答案 0 :(得分:1)

为了按输出表中提到浏览器的频率排序,你需要添加这样的计数,然后按计数列ORDER BY

SELECT *, count(browser) as frequency
FROM views 
WHERE linkid = '$string' 
GROUP BY browser
ORDER by frequency

答案 1 :(得分:0)

在Sql Query下面使用

SELECT * FROM `table` group by browser order by browser asc

使用PHP数组排序

排序($浏览器);