我想在JPA 2.1 Criteria API中编写这个SQL查询:
select * from t_question q
where
(select count(*) from t_question_tag tag
where
q.question_id = tag.question_id
AND tag.tag_id in (18, 1)
) = 2;
我无法弄清楚如何在内部查询中引用外部问题成员。
我目前正处于这一点:
CriteriaQuery<Question> cq = criteriaBuilder.createQuery(Question.class);
Root<Question> questions = cq.from(Question.class);
cq.distinct(true);
Subquery<Long> selectTags = cq.subquery(Long.class);
Root<QuestionTag> qt = selectTags.from(QuestionTag.class);
Join<QuestionTag, Question> qtJoin = qt.join("question");
selectTags
.select(criteriaBuilder.count(qtJoin))
.where(
qt.get("tag").in(filter.getTags())
);
cq.where(criteriaBuilder.and(insArray),
criteriaBuilder.equal(criteriaBuilder.literal(filter.getTags().size()), selectTags));
但它创造了第二个加入。 Sql结果是:
SELECT DISTINCT ...
FROM T_QUESTION question0_
WHERE 1 =
(SELECT COUNT(question3_.question_id)
FROM T_QUESTION_TAG questionta2_
INNER JOIN T_QUESTION question3_
ON questionta2_.question_id=question3_.question_id
WHERE questionta2_.tag_id IN (18));
答案 0 :(得分:1)
我希望子查询更像是
Subquery<Long> selectTags = cq.subquery(Long.class);
Root<QuestionTag> qt = selectTags.from(QuestionTag.class);
selectTags.select(criteriaBuilder.count(qt));
selectTags.where(
criteriaBuilder.equal(questions.get("id"), qt.get("id")),
qt.get("tag").in(filter.getTags())
);
使用外部查询中的候选项(“questions”)来引用外部查询,并且不知道为什么之前也进行了连接。我假设“问题”和“标签”中的字段都被称为“id”。