duansao6776 2013-03-01 17:38
浏览 11
已采纳

如何缩短功能查询?

hello i have this function:

function mail_exists($email){
    global $db;
    $email = sanitize($email);
    $query = $db->query("SELECT Email FROM table1 WHERE Email= '$email' ");
    $check = $query->num_rows;
    $query2 = $db->query("SELECT Email FROM table2 WHERE Email= '$email' ");
    $check2 = $query->num_rows;
    return ($check > 0 || $check2 > 0) ? true : false;
}

first of all i would like to know how i can shorten it by using only one query and second thing is, why this does not work when using two queries? both tables have a different structure. in table1 the field email is no. 16 and on table2 it is field no.6.

thanks alot.

  • 写回答

3条回答 默认 最新

  • duanguanzai6181 2013-03-01 17:47
    关注

    First of all you made a logic error *here in the last lines: $query->num_rows; should be: $query2->num_rows; and then resulting into:

    function mail_exists($email){
        global $db;
        $email = sanitize($email);
        $query = $db->query("SELECT Email FROM table1 WHERE Email= '$email' ");
        $check = $query->num_rows;
        $query2 = $db->query("SELECT Email FROM table2 WHERE Email= '$email' ");
        $check2 = $query2->num_rows; // *here
        return ($check > 0 || $check2 > 0) ? true : false;
    }
    

    Second, you should be using two different queries if you are dealing with two completely different contexts. Don't join queries when you don't need to. If you are just counting rows you can easily do:

    function mail_exists($email){
        global $db;
        $email = sanitize($email);
        $query = $db->query("SELECT COUNT(*) FROM table1 WHERE Email= '$email' ");
        $query2 = $db->query("SELECT COUNT(*) FROM table2 WHERE Email= '$email' ");
        $count1 = $query->fetch_row();
        $count2 = $query2->fetch_row();
        return ($count1[0] || $count2[0]);
    }
    

    The SQL COUNT() function is there to give you the most performant way to count rows.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题