作者热门文章
- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
我想在 Zend_Db 中生成这个复杂的 WHERE 子句:
SELECT *
FROM 'products'
WHERE
status = 'active'
AND
(
attribute = 'one'
OR
attribute = 'two'
OR
[...]
)
;
我试过了:
$select->from('product');
$select->where('status = ?', $status);
$select->where('attribute = ?', $a1);
$select->orWhere('attribute = ?', $a2);
然后产生:
SELECT `product`.*
FROM `product`
WHERE
(status = 'active')
AND
(attribute = 'one')
OR
(attribute = 'two')
;
我确实找到了一种方法来完成这项工作,但我觉得它有点“作弊”,即先使用 PHP 组合“OR”子句,然后使用 Zend_Db where() 子句组合它们。 PHP代码:
$WHERE = array();
foreach($attributes as $a):
#WHERE[] = "attribute = '" . $a . "'";
endforeach;
$WHERE = implode(' OR ', $WHERE);
$select->from('product');
$select->where('status = ?', $status);
$select->where($WHERE);
这产生了我正在寻找的东西。但我很好奇是否有一种“官方”方式通过使用 Zend_Db 工具来获得复杂的 WHERE 语句(实际上并不太复杂,只是添加一些括号),而不是先在 PHP 中组合它。
干杯!
最佳答案
这将是让您获得指定括号的“官方”方式(参见 Zend_Db_Select
文档中的示例 #20):
$a1 = 'one';
$a2 = 'two';
$select->from('product');
$select->where('status = ?', $status);
$select->where("attribute = $a1 OR attribute = $a2");
因此,鉴于您事先不知道自己拥有多少属性,因此您所做的似乎是合理的。
关于php - Zend_Db 使用多个 AND OR 运算符的复杂 WHERE 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4382602/
我是一名优秀的程序员,十分优秀!