Zend数据库优先处理Where语句

时间:2013-08-16 14:43:19

标签: php mysql sql zend-framework

我使用zend 1.12查询数据库以获取概述。现在我可以使用多个过滤器和搜索查询。这些都出现在这样的一个查询中:

SELECT `x`.`id`, `x`.`ref_id`, `x`.`start_date`, `x`.`regard`, `x`.`project_code`, `o`.`name` AS `contact`, `o`.`id` AS `contact_id`, `d`.`name` AS `department`, `c`.`name` AS `company`, `is`.`name` AS `status`, SUM(ip.price*ip.amount*(100-ip.discount)/100) AS `price_ex`, SUM(ip.price*ip.amount*(100-ip.discount)*(100+ip.tax)/10000)-IFNULL(p.payment,0) AS `price_open` FROM `invoice` AS `x`
 LEFT JOIN `contact` AS `o` ON x.recipient_id=o.id
 LEFT JOIN `department` AS `d` ON o.department_id=d.id
 LEFT JOIN `company` AS `c` ON d.company_id=c.id
 LEFT JOIN `invoice_status` AS `is` ON x.status=is.id
 LEFT JOIN `invoice_part` AS `ip` ON x.id=ip.invoice_id
 LEFT JOIN (SELECT SUM(amount) AS `payment`, `payment`.`invoice_id` FROM `payment` GROUP BY `invoice_id`) AS `p` ON x.id=p.invoice_id 
 WHERE (month(x.start_date) = '6') AND (year(x.start_date) = '2013') OR (LOWER(x.regard) LIKE '%test%') OR (LOWER(o.name) LIKE '%test%') OR (LOWER(c.name) LIKE '%test%') OR (LOWER(ref_id) LIKE '%test%') OR (LOWER(start_date) LIKE '%test%') GROUP BY `x`.`id` ORDER BY `x`.`updated_at` DESC LIMIT 50

现在所有过滤器都添加了AND,但是当我在列上搜索时,它会被添加为或,但现在找到了所有内容。我想要的是做[filter] AND [filter] AND ([search] or [search])。是否可以在我的zend查询中添加这些( )

1 个答案:

答案 0 :(得分:0)

是的,只需将所有OR位放入调用的地方:

$select->where('MONTH(x.start_date) = ?', $start_date_month)
       ->where('YEAR(x.start_date) = ?', $start_date_year)
       ->where('LOWER(x.regard) LIKE ? OR LOWER(o.name) LIKE ? OR LOWER(c.name) LIKE ? OR LOWER(ref_id) LIKE ? OR LOWER(start_date) LIKE ?', array($search, $search, $search, $search, $search));

此外,MySQL字符串比较默认情况下不区分大小写,除非您使用区分大小写的排序规则;所以LOWER()可能是不必要的(并且可能会阻止查询使用索引)。