The variant with join now works, but I want to get rid of group by in request. How to make a query with a subquery quantity in select?
SELECT t.id, t.title, (SELECT COUNT(t2.t2_id) FROM table2 t2 WHERE (t2.t2_id = t.id)) FROM table1 t option with join and group by - in my opinion - the best. if there is no specific need to get rid of join'a and group by - then leave!
// Not understood when creating a question, I am the author
This is the current used query with groupBy, trimmed. There is also a request for the amount of Project for page navigation. With join, an unequal number of records is obtained.
CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Project> cq = cb.createQuery(Project.class); Root<Project> root = cq.from(Project.class); Join atts = root.join("attachments", JoinType.LEFT); cq.select( cb.construct( Project.class, root.get("id"), root.get("regDate"), // другие поля cb.count(atts) ) ) .groupBy(root); // ============== groupBy TypedQuery<Project> typedQuery = em.createQuery(cq); The question is removed. Error in the code. It turned out that the left join root.join (the "attachments" which created the error is not equal to the number of projects in the sample request. The request is no longer needed. Thanks anyway.
Source: https://ru.stackoverflow.com/questions/624982/
All Articles
tadd a field (for example, t2_count) in which you store the number of records by a foreign key from tablet2. When adding records or deleting from tablet2update the corresponding field in tablet. This way you get rid of the subquery. - MrFylypenko