我需要创建一个查询,但这是一个困难的查询(至少是我)。
我的产品存储在数据库中,每一个都属于工厂。
每个工厂只能同时工作自己的一个产品。
每个产品都有一个数字,表示其在工厂队列中的订单。
每个产品都有一个字段--如果工厂已经开始处理它,它是一个数字;如果产品在队列中,则为null。
查询必须返回一个产品列表,其中包含每个工厂队列的第一个产品,但前提是工厂当前没有处理任何产品。
请参见以下示例:
Given:
Id FactoryId Working Order
Product1 Factory1 4654 1
Product2 Factory2 9841 3
Product3 Factory2 NULL 6
Product4 Factory3 NULL 4
Product5 Factory3 NULL 7
Product6 Factory4 NULL 2
Product7 Factory4 3211 9
product8 Factory5 NULL 10
product9 Factory5 NULL 5
product10 Factory5 NULL 13结果:
Id FactoryId Working Order
Product4 Factory3 NULL 4
product9 Factory5 NULL 5I使用Spring .
发布于 2018-06-28 14:43:14
您可以在关联子查询中使用NOT EXISTS:
select t.*
from table t
where not exists (select 1
from table t1
where t1.FactoryId = t.FactoryId and
t1.working is not null) and
Order = (select min(t1.order)
from table t1
where t1.FactoryId = t.FactoryId
);https://stackoverflow.com/questions/51085500
复制相似问题