我在Postgres中有以下查询:
SELECT *
from table1
LEFT OUTER JOIN table1.table2 ON table1.latest_id = table2.id
WHERE table1.table2.status = 0
AND table1.id NOT IN (
(SELECT id from table3 where userId = table2.user))
我不具备连接table1和table3的能力,并且无法以JPA可以理解的格式编写子查询-使用Spring Boot应用程序。这是到目前为止我的存储库类中的位置:
@Query("SELECT c FROM #{#entityName} c JOIN FETCH c.table2 WHERE c.table2.status = 0")
fun findByIdAndStatus(id: String): MyEntity
我尝试如下进行子查询,但是没有喜悦-存在明显的语法错误,我无法解决问题:
@Query("SELECT c FROM #{#entityName} c JOIN FETCH c.table2 WHERE c.table2.status = 0" AND c.id NOT IN (" +
"SELECT * FROM Table3 WHERE userId = c.table2.user")
你能帮忙吗?
谢谢
答案 0 :(得分:1)
假设:
MyEntity
映射,而table3被Table3
实体MyEntity
连接列在latest_id
中映射与table2关联的您可以将查询重写为以下JPQL格式:
@Query("SELECT t1 FROM MyEntity t1 "
+ "JOIN t1.table2 t2 "
+ "WHERE t2.status = 0 AND t1.id NOT IN ("
+ " SELECT t3.id from Table3 t3 "
+ " WHERE t3.userId = t2.user "
+ ")")
List<MyEntity> findMyEntities();