加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 如何使这个MySQL Count查询更有效?

发布时间:2020-12-13 17:07:16 所属栏目:PHP教程 来源:网络整理
导读://get the current member count$sql = ("SELECT count(member_id) as total_members from exp_members");$result = mysql_query($sql) or die(mysql_error());$num_rows = mysql_num_rows($result);if ($num_rows != 0) { while($row = mysql_fetch_array($
//get the current member count
$sql = ("SELECT count(member_id) as total_members from exp_members");
$result = mysql_query($sql) or die(mysql_error());
$num_rows = mysql_num_rows($result);
if ($num_rows != 0) {
    while($row = mysql_fetch_array($result)) {
        $total_members = $row['total_members'];
    }
}

//get list of products
$sql = ("SELECT m_field_id,m_field_label from exp_member_fields where m_field_name like 'cf_member_ap_%' order by m_field_id asc");
$result = mysql_query($sql) or die(mysql_error());
$num_rows = mysql_num_rows($result);

if ($num_rows != 0) {

    while($row = mysql_fetch_array($result)) {

        $m_field_id             = $row['m_field_id'];
        $m_field_label          = $row['m_field_label'];

        $sql2 = ("SELECT count(m_field_id_".$m_field_id.") as count from exp_member_data where m_field_id_".$m_field_id." = 'y'");
        $result2 = mysql_query($sql2) or die(mysql_error());
        $num_rows2 = mysql_num_rows($result2);

        if ($num_rows2 != 0) {
            while($row2 = mysql_fetch_array($result2)) {
                $p = ($row2['count']/$total_members)*100;
                $n = $row2['count'];
                $out .= '<tr><td>'.$m_field_label.'</td><td>'.number_format($p,1).'%</td><td>'.$n.'</td></tr>';
            }
        }

    }


}

解决方法

count查询总是会返回1行,所以你不需要循环

$sql = ("SELECT count(member_id) as total_members from exp_members");
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($result);
$total_members = $row['total_members'];

除此之外我不知道你怎么能让它变得更好.您可以对两个计数查询执行相同的操作.

由于这些都是直接查询,我现在认为任何瓶颈都会出现在MySQL端

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读