我试图在select子句中配置一个子查询,以实现如下sql等价项:
SELECT
t0.field1 AS a1,
t0.field2 AS a2,
t0.field3 AS a3,
t0.field4 AS a4,
t0.field5 AS a5,
(SELECT COUNT(t1.id) from table1 t1 WHERE t1.field1t1 = t2.field1t2) AS a6
FROM
table0 t0,
table2 t2
WHERE
(t2.field1t2 = t0.field5)
我找到了一些关于如何做到这一点的参考资料,比如:
select子句中带有jpa条件api的子查询
因此,我在jpa实现中构建了一个tuplequery,以便首先获取一个实体(在上一个sql示例中,所有字段-a1..a5-来自table0),然后获取count字段(a6):
CriteriaBuilder cb = em.getCriteriaBuilder();
// Main Query
CriteriaQuery cq = cb.createTupleQuery();
Root<EntityTable0> root = cq.from(EntityTable0.class);
// Subquery
Subquery sub = cq.subquery(Long.class);
Root<EntityTable1> subRoot = sub.from(EntityTable1.class);
Path<EntityTable2> pathTable2 = root.get("field4");
Predicate conditionSubquery = cb.equal(subRoot.get("field1t1"), pathTable2.get("field1t2"));
// Select on the subquery
sub.select(cb.count(subRoot)).where(conditionSubquery);
// Multi-select on main TupleQuery
cq.multiselect(root, sub.getSelection());
当我运行上述jpa代码时,得到的结果是:
SELECT
t0.field1 AS a1,
t0.field2 AS a2,
t0.field3 AS a3,
t0.field4 AS a4,
t0.field5 AS a5,
COUNT(t1.id)
FROM
table0 t0,
table2 t2,
table1 t1
因此,基本上不执行子查询,甚至不考虑“condicinsubquery” predicate 。
我做错什么了?我测试了sql,它按预期工作。
我使用的是jpa的eclipselink 2.7实现。
暂无答案!
目前还没有任何答案,快来回答吧!