如何在内部查询中引用外部查询的成员?
How to reference a member of outer query in a inner query?
我想在 JPA 2.1 条件中编写此 SQL 查询 API :
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));
但是它创建了第二个 Join。 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));
我希望子查询更像这样
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") 来引用外部查询,也不明白您之前为什么要进行连接。我假设 "Question" 和 "Tag" 中的字段都称为 "id".
我想在 JPA 2.1 条件中编写此 SQL 查询 API :
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));
但是它创建了第二个 Join。 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));
我希望子查询更像这样
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") 来引用外部查询,也不明白您之前为什么要进行连接。我假设 "Question" 和 "Tag" 中的字段都称为 "id".