dongzz4545 2014-03-27 22:09
浏览 308
已采纳

使用where子句和if语句进行MySQL查询

I'm stuck again on a MySQL query and I would like some help.

I am trying to find the best possible way to do this. What I want to do is check if $var = 'x' and based on that run a different query.

Part of the code:

if ($var1 == '0' AND $var2 != '0' AND $var3 != '0' AND $var4 != '0') {
    echo $query = "SELECT * FROM table WHERE var1 = ''";
}elseif ($var1 == '1' AND $var2 != '0' AND $var3 != '0' AND $var4 != '0') {
    echo $query = "SELECT * FROM table WHERE var1 = '1'";
}elseif ($var1 != '0' AND $var2 == '0' AND $var3 != '0' AND $var4 != '0') {
    echo $query = "SELECT * FROM table WHERE var2 = ''";
}elseif ($var1 == '0' AND $var2 == '0' AND $var3 != '0' AND $var4 != '0') {
    echo $query = "SELECT * FROM table WHERE var1 = '' AND var2 = ''";
} etc..

The connections are a LOT. Is there a better way to do this? Pretty much each variable (in total 7) got 3 different choices. I can't put var = $var under the WHERE clause because sometimes when $var = '0' I mean all the results so I don't even put it there..

This is a filtering script/code by the way..

Does this even make sense to you? Thanks!

  • 写回答

3条回答 默认 最新

  • douzhicai7148 2014-03-27 22:18
    关注

    I think this can be done with a single query and varying WHERE conditions. You need to first define when to put var1 = '' in your WHERE clause. You should find out the cases when you need varX = '' in your query one by one.

    $conds = array();
    if ($var1 == '0' || $var2 == '0') {
      $conds[] = "var1 = ''"; // this should be the only point where var1 is included in your query, so you need to have every possible condition in this if part
    }
    if ($var3 == '0' && $var4 != '0') {
      $conds[] = "var3 = ''";
    }
    // ..etc..
    $query = "SELECT * FROM TABLE WHERE " . implode(' AND ', $conds);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料