在已加入的查询上转换为JPA别名SELECT

时间:2014-07-23 06:38:25

标签: java jpa

对于表格结构:

问题

id

question

学生

id

name

ANSWER

id

question_id

student_id

目标: 获得给定学生的所有已回答和未答复的问题

在MYSQL中尝试和测试的SQL

SELECT * FROM question q 
LEFT JOIN 
(SELECT * FROM answer a WHERE a.student_id=?) AS answered 
ON q.id = answered.question_id;

如何将此转换为JPA?

1 个答案:

答案 0 :(得分:0)

抵消,请阅读:

http://docs.oracle.com/javaee/7/tutorial/doc/partpersist.htm#BNBPY

SELECT a.question FROM Answer a WHERE a.student.id = :studentId;

如果你真的想使用别名手动选择:

SELECT q FROM Question q WHERE EXISTS(SELECT a FROM Answer a WHERE a.question.id = q.id);