在单个查询中使用OR,AND运算符

时间:2017-07-22 03:26:44

标签: php mysql

我正在尝试列出符合我条件的记录。由于我正在使用ANDOR运算符,因此我无法获得确切的报告。这是我的查询

SELECT o.sales_order_id AS SID, o.reference, o.status, o.last_modified, sol.sales_order_id, sol.item, sol.quantity, sol.selling_price, sol.discount, sol.tax, SUM(sol.tax_amount) AS Tamt, SUM(sol.total) as Total, i.iid, GROUP_CONCAT(DISTINCT i.name) AS iname, l.company, t.tax_id, t.name as tname, t.rate from orders o INNER JOIN before_order_line_items sol ON o.sales_order_id = sol.sales_order_id INNER JOIN leads l ON o.company_id=l.id INNER JOIN items i ON sol.item=i.iid INNER JOIN taxes t ON sol.tax=t.tax_id WHERE o.order_quote='Order' AND o.authorise='Yes' OR o.assigned_to=6 OR o.user_id=6 GROUP BY o.sales_order_id ORDER BY o.sales_order_id DESC

我将订单和报价存储在单个表Orders中,对于我将其存储在order_quote列中的Order的订单,对于报价Quote

它没有检查order_quote='Order'条件,它显示订单和报价。

如果我删除OR o.assigned_to=6 OR o.user_id=6,它会给出正确的结果。

我尝试使用像这样的DISTINCT

SELECT DISTINCT o.order_quote=`Order`, .....  

但是不起作用。

已更新

SELECT o.sales_order_id AS SID, o.reference, o.status, o.last_modified, sol.sales_order_id, sol.item, sol.quantity, sol.selling_price, sol.discount, sol.tax, SUM(sol.tax_amount) AS Tamt, SUM(sol.total) as Total, i.iid, GROUP_CONCAT(DISTINCT i.name) AS iname, l.company, t.tax_id, t.name as tname, t.rate from orders o INNER JOIN before_order_line_items sol ON o.sales_order_id = sol.sales_order_id INNER JOIN leads l ON o.company_id=l.id INNER JOIN items i ON sol.item=i.iid INNER JOIN taxes t ON sol.tax=t.tax_id WHERE (o.order_quote='Order' AND o.authorise='Yes') AND (o.assigned_to=6 OR o.user_id=6) GROUP BY o.sales_order_id ORDER BY o.sales_order_id DESC 

1 个答案:

答案 0 :(得分:1)

您需要使用括号。我不确定具体如何,但您当前的where子句被解释为:

WHERE (o.order_quote = 'Order' AND o.authorise = 'Yes') OR
      (o.assigned_to = 6) OR
      (o.user_id = 6)

我猜你想要这样的东西:

WHERE (o.order_quote = 'Order' AND o.authorise = 'Yes') AND
      (o.assigned_to = 6 OR o.user_id = 6)

但这仅仅是猜测。

或者也许:

WHERE (o.order_quote = 'Order' AND
      (o.authorise = 'Yes' OR o.assigned_to = 6 OR o.user_id = 6)