1

我有以下表格:

actions(id, name)
orders(refno, po)
order_actions(order, action)

我想获取尚未执行特定操作的所有订单。订单可能包含或不包含操作。

假设我想获取所有尚未应用 action 的订单,13到目前为止我有这样的东西:

SELECT o.po, oa.action, 
    FROM orders AS `o`
    LEFT JOIN order_actions AS `oa` ON o.refno = oa.order
WHERE oa.action <> 13

这适用于没有操作的订单,但如果订单的操作与13我得到误报不同,我是否错过了另一个涉及actions表的连接,可能是GROUP BY用于 po 或额外的WHERE子句?

任何帮助表示赞赏。

4

3 回答 3

3
SELECT o.po, oa.action
FROM orders AS `o`
     LEFT JOIN order_actions AS `oa` ON o.refno = oa.order
WHERE NOT EXISTS (
  SELECT 1 
  FROM order_actions tmp 
  WHERE oa.order = tmp.order 
    AND tmp.action = '13'
)

演示(sqlfiddle)。

于 2012-08-22T00:29:27.953 回答
1

您还可以使用 group by 和 having 子句解决此问题:

SELECT o.refno, o.po
FROM orders AS `o` LEFT JOIN
     order_actions `oa`
     ON o.refno = oa.order
group by o.refno, o.po
having max(case when oa.action = 13 then 1 else 0 end) = 0

如果要跟踪此类订单的所有操作,可以使用 group_concat:

SELECT o.refno, o.po,
       group_concat(cast(ao.action) separator ', ') as AllOtherActions
FROM orders AS `o` LEFT JOIN
     order_actions `oa`
     ON o.refno = oa.order
group by o.refno, o.po
having max(case when oa.action = 13 then 1 else 0 end) = 0
于 2012-08-22T01:59:08.743 回答
0

另一种选择是:

select o.po
from orders as 'o'
    left join (
        select order from order_actions where [action] = @Action
        ) AS `oa` on o.refno = oa.order
where oa.order is null

这不会返回您选择的订单的操作编号,但您已声明您只是在寻找尚未执行操作的订单,我在此将其称为 @Action

于 2012-08-22T02:07:06.523 回答