组行,按分组行计数分组行和顺序

时间:2015-09-01 09:09:11

标签: php sql

我想为网站制作一个分析系统,我正在尝试从数据库中按行分组,按网址分组,计算分组行数,并按分组行数对DESC进行排序。

$sql = "SELECT COUNT(*) FROM (SELECT DISTINCT url FROM analytic) ORDER by (SELECT DISTINCT url FROM analytic)";
$countQry  = mysqli_query($link, $sql);

while($arr = mysqli_fetch_array($countQry)) {
?>
    <?=$arr['url']?>

<?
    }
?>

感谢

1 个答案:

答案 0 :(得分:1)

尝试使用GROUP BY

SELECT url, COUNT(url) AS theCount
FROM analytic
GROUP BY url
ORDER BY theCount DESC

以下是您可以使用的PHP代码:

$sql = "SELECT url, COUNT(url) AS theCount FROM analytic GROUP BY url ORDER BY by theCount DESC";
$countQry  = mysqli_query($link, $sql);
while ($row = mysqli_fetch_array($countQry, MYSQLI_ASSOC)) {
    echo $row['url'], ", ", $row['theCount'];
}