简体   繁体   English

MySQL计数表列中的重复项

[英]MySql count duplicates in column of a table

I have a table named telco which has 2 columns, id(PK) and telco_prov . 我有一个名为telco的表,它具有2列id(PK)telco_prov I want to count the duplicate records in the telco_prov column, then display the number of times it appeared. 我想计算telco_prov列中的重复记录,然后显示它出现的次数。

telco table example: telco例:

id    telco_prov
1     Smart
2     Smart
3     Globe
4     Globe
5     Globe

Here is my code: 这是我的代码:

    $query = "select telco_prov, count(*) c from telco group by telco_prov having c > 1";
    $result = mysql_query($query) or die('Error: '.mysql_error ());
    $row = mysql_fetch_assoc($result);

    echo "SMART: <font color= 'red'>".$row['c']."</font>";
    echo "<br>GLOBE: <font color= 'red'>".$row['c']."</font>";

The code has no error, but it doesn't do the counting correctly. 代码没有错误,但是没有正确计数。

The result from the code above: 上面代码的结果:

SMART: 2
GLOBE: 2

But it should be: 但是应该是:

SMART: 2
GLOBE: 3

I've tried adding where statement in the query but still it doesn't work. 我尝试在查询中添加where语句,但仍然无法正常工作。

$query = "select telco_prov, count(*) c from telco where telco_prov = 'Smart' group by telco_prov having c > 1";

Your help would be much appreciated. 您的帮助将不胜感激。 Thanks! 谢谢!

You have to loop the results. 您必须循环结果。 see the below code 见下面的代码

$query = "select telco_prov, count(*) c from telco group by telco_prov having c > 1";
$result = mysql_query($query) or die('Error: '.mysql_error ());
while($row = $mysql_fetch_assoc($result)) {
    echo $row['telco_prov'].": <font color= 'red'>".$row['c']."</font>";
}

Try with 试试看

while($row = mysql_fetch_assoc($result)){
  echo strtoupper($row['telco_prov']).": <font color= 'red'>".$row['c']."</font>";
}

The code you write will give only the first row. 您编写的代码将仅给出第一行。 For getting all the records, you need to loop though the record 为了获取所有记录,您需要遍历记录

the error is here 错误在这里

echo "SMART: <font color= 'red'>".$row['c']."</font>";
echo "<br>GLOBE: <font color= 'red'>".$row['c']."</font>";

this code will echo all telco_prov with their counts 该代码将回显所有telco_prov及其计数

while ($row = mysql_fetch_assoc($result)) {
   echo '"'.$row['telco_prod'].'"':<font color="red">'.$row['c'].'</font>';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM