使用COUNT& PHP分页不同

时间:2013-05-25 10:13:40

标签: php

我有一个PHP分页系统,我想要做的是使用Distinct只返回唯一值,会发生什么是页面显示应该有多少页但是没有给我任何结果。< / p>

我的代码在这里

$query = "SELECT DISTINCT ip_address, 
                 COUNT(*) as num 
          FROM $tableName  
          WHERE hostname 
          LIKE 'mail%' AND type='6'";
$total_pages = mysql_fetch_array(mysql_query($query));
$total_pages = $total_pages[num];

$stages = 3;
$page = mysql_escape_string($_GET['page']);

if($page){
    $start = ($page - 1) * $limit; 
}else{
    $start = 0; 
}   

// Get page data
$query1 = "SELECT DISTINCT ip_address, 
                  hostname 
            FROM masterip_details  
                WHERE hostname 
            LIKE 'mail%' AND type='6' 
                LIMIT $start, $limit";
$result = mysql_query($query1);

2 个答案:

答案 0 :(得分:0)

您应该将DISTINCT放在COUNT函数中,以计算$tableName表中唯一IP地址的数量。像这样:

$query = "SELECT COUNT(DISTINCT ip_address) as num 
             FROM $tableName  
             WHERE hostname 
             LIKE 'mail%' AND type='6'
         ";

答案 1 :(得分:0)

如果ip_address字段中没有索引,我只使用SELECT COUNT(DISTINCT ip_address) as num。如果您拥有索引,您也可以这样做:

SELECT COUNT(type) AS num FROM tbl WHERE hostname LIKE 'mail%' and type = 6 GROUP BY ip_address;

因为,如果您要对索引进行分组,DISTINCT相当于GROUP BYMore details herehere

我回答这个问题的真正原因是:don't use the deprecated mysql_* extension。使用其中一个替换mysqli_*, with i for improvedPDO, which seems to be more commonly used