JPA查询,选择包含两个或更多批准评论的文章

时间:2015-11-26 18:48:55

标签: sql jpa

每篇文章都有三篇评论;审核已“批准”列(true表示审核接受文章,false表示拒绝)。如何选择有两个或两个以上批准的评论的文章?

mysql> describe article;
+--------------+--------------+------+-----+---------+----------------+
| Field        | Type         | Null | Key | Default | Extra          |
+--------------+--------------+------+-----+---------+----------------+
| id           | int(11)      | NO   | PRI | NULL    | auto_increment |
| content      | longtext     | NO   |     | NULL    |                |
| author_id    | int(11)      | NO   | MUL | NULL    |                |
+--------------+--------------+------+-----+---------+----------------+

mysql> describe review;
+-------------+--------------+------+-----+---------+----------------+
| Field       | Type         | Null | Key | Default | Extra          |
+-------------+--------------+------+-----+---------+----------------+
| id          | int(11)      | NO   | PRI | NULL    | auto_increment |
| comment     | varchar(255) | YES  |     | NULL    |                |
| approved    | tinyint(1)   | YES  |     | NULL    |                |
| article_id  | int(11)      | YES  | MUL | NULL    |                |
| reviewer_id | int(11)      | YES  | MUL | NULL    |                |
+-------------+--------------+------+-----+---------+----------------+
5 rows in set (0.01 sec)

这里我想在JPA Reporsitory中使用查询:

public interface ArticleRepository extends JpaRepository<Article, Integer>{

    @Query("XXXXXXXXXXXXXX")
    public List<Article> findApprovedArticles();
}

1 个答案:

答案 0 :(得分:1)

您可以使用相关子查询:

"select a from Article a where
    (select count(*) from Review r where r.articleId = a.id and r.approved = 1) >= 2"