使用GROUP BY,HAVING和COUNT进行JPA查询

时间:2016-06-10 14:06:01

标签: jpa jpql

所以下面的查询可能不是最有效的,买还是,我想知道为什么它没有返回结果,即使SQL对应的确实如此。没有错误,我只是没有结果。它可能不是我在MySQL中编写的查询的正确等价物吗?

这是JPA JPQL。

Query query = em.createQuery("SELECT sub FROM Subscription sub WHERE "
                + "sub.isSuspended = 0 AND "
                + "(SELECT i FROM Invoice i WHERE i.dateDue < CURRENT_DATE AND i.datePaid IS NULL "
                + "GROUP BY i HAVING COUNT(i.idInvoice) > 2) MEMBER OF sub.invoices");

这是来自MySQL的SQL。

SELECT * from subscription 
WHERE subscription.is_suspended = 0 AND id_subscription IN 
    (SELECT id_subscription FROM invoice 
    WHERE date_due < CURDATE() AND date_paid IS NULL
    GROUP BY id_subscription
    HAVING COUNT(*) > 2)

1 个答案:

答案 0 :(得分:1)

两个查询不一样。要使用实际查询,请使用 NativeQuery createNativeQuery()代替Query。

在您的情况下,JPA版本似乎有语法错误。

  1. 在AND之后你缺少IN操作符。
  2. 在嵌套查询中,您选择的是i,而不是i.idInvoice
  3. JPA查询应该看起来像

    SELECT sub FROM Subscription sub WHERE sub.isSuspended = 0 AND 
    sub.idSubscription IN (SELECT i.idInvoice FROM Invoice i WHERE 
    i.dateDue < CURRENT_DATE AND i.datePaid IS NULL GROUP BY i.idInvoice 
    HAVING COUNT(i.idInvoice) > 2);