我有一个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);
答案 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 BY
。 More details here和here。
我回答这个问题的真正原因是:请,don't use the deprecated mysql_*
extension。使用其中一个替换mysqli_*
, with i
for improved或PDO, which seems to be more commonly used。