mysql - 仅获取某些值 (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 的订单?都在同一个查询中。
解决方案
您可以使用聚合:加入table1
,table2
然后左加入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
推荐阅读
- reactjs - getData() 缺少图像 src 属性
- r - 在 Shiny 中创建条件 menuitems 和 menuSubItems
- powershell - VSC 在运行 powershell 脚本时抛出错误
- javascript - 在选择更改事件上反应提交表单
- azure-cosmosdb - 如何在 TinkerPop3 中组合选择节点?
- sql - 在 SQL 中生成 Pivot(按小时划分的每个部门的销售额)
- linux - 检索“ls -la”的符号链接和目标链接
- c# - iText 7 - 居中对齐文本和段落
- javascript - 如何在Angular 6中为反应形式设置日期默认值?
- python - 如何从 Excel 或 .csv 文件中读取带有一个标题的两列?