我有下一个SQL查询
SELECT cb.id cbId, cb.name cbName, d.id drugId, d.name drugName, array_agg(sel.id) dependencyDrugIds
FROM businesses cb
LEFT JOIN scenarios s ON cb.id = s.cb_id
LEFT JOIN drugs d ON s.id = d.scenario_id
LEFT JOIN (SELECT d2.id, s2.dependency_id
FROM scenarios s2
LEFT JOIN drugs d2 ON s2.id = d2.scenario_id
WHERE s2.dependency_id is not null
ORDER BY d2.id) sel on s.dependency_id = sel.dependency_id
GROUP BY cb.id ,cb.name , d.id, d.name
我尝试将其重构为基于CriteriaBuilder的查询 但是我不知道如何创建子查询。以及如何将其加入dependency_id字段
有可能吗?这就是我所拥有的
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<DrugCbDependenciesDto> criteriaQuery = cb.createQuery(DrugCbDependenciesDto.class);
Root<Business> cbRoot = criteriaQuery.from(Business.class);
Join<Business, Scenario> scenarioJoin = cbRoot.join(Business_.scenarios, LEFT);
Join<Scenario, Drug> drugJoin = scenarioJoin.join(Scenario_.drugs, LEFT);
Subquery<List> subquery = criteriaQuery.subquery(List.class);
Root<Scenario> subRoot = subquery.from(Scenario.class);
Join<Scenario, Drug> subScenarioJoin = subRoot.join(Scenario_.drugs, INNER);
Join<Scenario, Dependency> subDependencyJoin = subRoot.join(Scenario_.dependency, INNER);
subquery.select(subRoot.get(Dependency_.id.getName()));