dongluedeng1524 2013-01-05 20:07
浏览 254
已采纳

我可以在一个MySQL查询中使用多个WHERE语句吗?

Disclaimer: I know it's possible to add AND and OR operators into a single WHERE statement, and this is generally the proper way to do it...

However, I'm building a complex query dynamically based on a variety of external factors. For the purposes of readability and and maintainability, it would be a lot tidier if I could have have one WHERE statement for certain conditions that always need to be met, but then add another (second) one later that will change depending on the circumstances.

A. Is this valid MySQL? B. Is it a terrible idea for some particular reason?

Here's a simplified example:

<?php 
$query = "
SELECT a,b,c
FROM table1
LEFT JOIN table2 on foo=bar
LEFT JOIN table3 on foo2=bar2
...
WHERE foobar = something_that_is_consistent 
AND boobar = something_else_consistent
...
";

if ( $something_special ) {
$query .= "WHERE ..."
}

if ( $something_else_special ) {
$query .= "WHERE ..."
}

This is a trivial example, but hopefully it demonstrates what I'm thinking about and how I'm trying to avoid big gangly nested conditionals inside the query string.

  • 写回答

3条回答 默认 最新

  • dtvam48220 2013-01-05 20:12
    关注

    your WHERE should be one and then use AND

       <?php 
       $query = "
     SELECT a,b,c
     FROM table1
     LEFT JOIN table2 on foo=bar
     LEFT JOIN table3 on foo2=bar2
     ...
     WHERE foobar = something_that_is_consistent 
     AND boobar = something_else_consistent
     ...
     ";
    
    if ( $something_special ) {
     $query .= "AND ..."
     }
    
     if ( $something_else_special ) {
     $query .= "AND ..."
     }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵