首页 > 解决方案 > 仅获取某些值 (sql)

问题描述

我有 3 个不同的表:table1、table2、table3

表 1包含已购买的所有不同订单

表 2包含每个订单的详细信息(我的意思是,它包含一个名为ORDER_DETAIL的列,数字代表该订单的一个项目 - 一个唯一值)

表 3包含工作流。表 2 中的 ORDER_DETAIL 中的一些数字将出现在此处,因为该项目必须经过批准才能交付

我想获取所有项目未出现在表 3 中的不同订单。

这张图说明了一切:

图片

这是我的 SQLFIDDLE:http ://sqlfiddle.com/#!9/5bfc22/2

我做了这个查询,但我没有得到我想要的:

select * from table1 kio
inner join table2 jio on kio.ORDER_NUMBER = jio.ORDER_NUMBER
where jio.CANCELLED = 0
and not exists (select 1 from table3 gio where jio.ORDER_DETAIL = gio.ORDER_DETAIL)

另外,我如何获得那些 ORDER_DETAILs 仅出现在表 2的订单以及那些 order_details 出现在表 3 中且 PROCESSED = 1 和 APPROVED = 1 的订单?都在同一个查询中。

标签: mysqlsqljoin

解决方案


您可以使用聚合:加入table1table2然后左加入table3,聚合order_number和过滤在 中没有匹配的组table3

select t1.id, t1.order_number
from table1 t1
inner join table2 t2 on t2.order_number = t1.order_number
left join table3 t3 on t3.order_detail = t2.order_detail
group by t1.id, t1.order_number
having count(t3.order_detail) = 0

在您的 DB Fiddle 中,这会产生:

id  order_number
3   46646

另外,我如何获得那些 ORDER_DETAILs 仅出现在表 2 中的订单以及那些 order_details 出现在表 3 中且 PROCESSED = 1 和 APPROVED = 1 的订单?都在同一个查询中

为此,您可以在having子句中添加另一对条件:

having 
    count(t3.order_detail) = 0
    or (max(t3.processed) = 1 and max(t3.approved) = 1)

产量:

id  order_number
1   78945
3   46646

推荐阅读