如何使用子查询编写此JPQL查询?

时间:2014-08-20 08:18:24

标签: java sql jpa subquery jpql

我正试图引用那句SQL句子

SELECT 
  operationalobjective.idoperationalobjective, 
  pno_oo.name
FROM 
  public.operationalobjective, 
  public.policynamedobject pno_oo
WHERE
  pno_oo.idpolicynamedobject = operationalobjective.idoperationalobjective AND
  operationalobjective.idoperationalobjective NOT IN
(
SELECT 
  operationalobjective.idoperationalobjective  
FROM 
  public.operationalobjective, 
  public.goal, 
  public.policy, 
  public.policynamedobject pno_oo, 
  public.policynamedobject pno_p
WHERE 
  goal.idpolicy = policy.idpolicy AND
  goal.idoperationalobjective = operationalobjective.idoperationalobjective AND
  pno_oo.idpolicynamedobject = operationalobjective.idoperationalobjective AND
  pno_p.idpolicynamedobject = policy.idpolicy AND
  policy.idpolicy = <number>
);

考虑到Policy和OperationalObjective都扩展了PolicyNamedObject,我试图将其引入JPQL:

SELECT oo FROM OperationalObjective oo 
WHERE oo.idoperationalobjective NOT IN 
(
   SELECT oo.idoperationalobjective 
   FROM OperationalObjective oo, Goal g, Policy p 
   WHERE g.policy = :policy AND g.operationalobjective = oo AND p = :policy
)

但是当我通过JPA执行该查询时,它引发了一个异常说:

ERROR: missing FROM-clause entry for table <<t5>>  
  SELECT t7.idpolicynamedobject, t7.type, t7.description, t7.name, t0.idoperationalobjective, t0.idobjectivescategory 
    FROM public.OperationalObjective t0 INNER JOIN public.PolicyNamedObject t7 ON t0.idoperationalobjective = t7.idpolicynamedobject 
    WHERE (NOT (t0.idoperationalobjective IN 
    (
        SELECT t5.idoperationalobjective 
            FROM public.OperationalObjective t1 CROSS JOIN public.Goal t2 CROSS JOIN public.policy t3 
                INNER JOIN public.PolicyNamedObject t4 ON t3.idpolicy = t4.idpolicynamedobject 
                INNER JOIN public.PolicyNamedObject t6 ON t5.idoperationalobjective = t6.idpolicynamedobject, public.OperationalObjective t5 
            WHERE (t2.idpolicy = ? AND t2.idoperationalobjective = t5.idoperationalobjective 
                AND t3.idpolicy = ?) AND t6.type = ?))) AND t7.type = ?} [code=0, state=42P01]

我已经使用PgAdmin执行了SQL语句并且它检索了我想要的内容,但是我不知道我在做什么错误将它翻译成JPQL ...任何想法?

提前谢谢你:)

1 个答案:

答案 0 :(得分:0)

我怀疑你需要重构你的JPQL语句以使用子查询'EXISTS',因为IN语句不支持子选择。希望这会指出你正确的方向。

SELECT oo FROM OperationalObjective oo 
WHERE NOT EXISTS 
(
   SELECT oosub
   FROM OperationalObjective oosub
   JOIN oosub.goal g 
   JOIN g.policy p   
   WHERE <<where conditions>> 
) 

Oracle docs