我正在使用 JPA 查询条件来构建一个在同一个表上进行联接的查询。该表如下所示。
Table A
Id EventType
A Start
A Start
A End
B Start
C Start
C End
我想找出相同 Id 的 EventType 为 Start 且没有 EventType End 的所有行。 在 SQL 中:我通过如下连接得到了这个:
select DISTINCT *
from (select *
from A
where Id='A'
AND EventType = 'Start') startEventTable
LEFT JOIN (select *
from A
where Id='A'
AND EventType = 'endEvent') endEventTable
ON (startEventTable.Id = endEventTable.Id)
WHERE endEventTable.Id IS NULL;
我无法在 JPA 中实现这一点
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery cq = cb.createQuery(A.class);
Root<A> r1 = cq.from(A.class);
SubQuery sq1 = cq.subquery(A.class);
SubQuery sq2 = cq.subquery(A.class);
Root<A> r2 = sql.from(A.class);
Root<A> r3 = sq2.from(A.class);
sq1.where(<predicate>);
sq2.where(<predicate>);
cq.where(cb.and(cb,exists(sq1), cb.exists(sq2).not()));
New TypedQuery(cq).getResultList();
此操作因多个路径异常而失败。我对 JPA 查询不熟悉,请在此处请求有人提供帮助。
最佳答案
使用以下更简单、更快的查询之一:
SELECT DISTINCT * -- you probably don't need DISTINCT
FROM A
WHERE Id = 'A'
AND EventType = 'Start'
AND NOT EXISTS (
SELECT 1
FROM A a1
WHERE a1.Id = A.Id
AND EventType = 'endEvent'
);
或者
SELECT DISTINCT * -- you probably don't need DISTINCT
FROM A
LEFT JOIN A a1 ON a1.Id = A.Id
AND a1.EventType = 'endEvent'
WHERE A.Id = 'A'
AND A.EventType = 'Start'
AND a1.Id IS NULL;
详细信息:
关于java - 同一张表上的左连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25077196/