I wonder if there is a way to phrase something like
SELECT `sum(<field>)` FROM (SELECT field from ... WHERE ...)
in QueryDSL(Version 4.x).
Let's say I have an Article "green Balloon" in all my Stores and I need to know how many "green Balloon" I have in total (I know it's a stupid example but it will do ;)).
The SQL could look like:
SELECT count(a.id)
FROM (
SELECT art.id
FROM article art
LEFT JOIN store s ON (art.storeId = s.id)
WHERE art.name = 'green Balloon'
GROUP BY s.id
) a;
How can I translate said SQL to QueryDSL?
Edit: As it was subject to confusion: Yes, the example is stupid. No I do not want to 'optimize' the SQL. All I need is some QueryDSL-Code generating the exact same (stupid) SQL. Or any other QueryDSL-Code generation any sort of SELECT ... FROM (SELECT ...)
for that matter. If that is even possible.
There is a two year old post handling this topic, but apparently it was not possible then. Maybe it is now?
SELECT count(*) FROM article art LEFT JOIN store s ON (art.storeId = s.id) WHERE art.name = 'green Balloon'
do you what you need? Why do you need to select from a select for that query?SELECT COUNT(*) FROM (SELECT ...)
seems like overkill. Something likeSELECT SUM(a.quantity) FROM article a WHERE a.name = 'green Balloon'
would suffice for the provided example. This simplified query can be expressed in QueryDSL asnew JPAQuery<Article>(entityManager).from(QArticle.article).where(QArticle.article.name.equals("green Balloon").select(QArticle.article.quantity.sum()).fetchOne()
. Note that anEntityManager
instance is required to instantiate aJPAQuery
in this case.