I'm creating a request to the database using QueryDSL. After some time, I finally got the correct QueryDSL to request, but I was thinking why the following query is the opposite of the SQL version of it, and I can't find an answer.
Example, a SQL query:
SELECT n.id, network_name, count(DISTINCT a.id), count(DISTINCT w.id), count(DISTINCT v.id)
FROM network n
LEFT JOIN account a ON a.network_id = n.id
LEFT JOIN meat w ON w.account_id = a.id
LEFT JOIN fish v ON v.account_id = a.id
GROUP BY n.id, network_name
To get the same results on QueryDSL, I need to specify the query in the following format:
new JPAQuery(entityManager).from(meat, fish)
.rightJoin(meat.account, account)
.rightJoin(fish.account, account)
.rightJoin(account.network, network)
.groupBy(network)
.where(network.id.eq(id))
.singleResult(network, account.id.countDistinct(), fish.id.countDistinct(), meat.id.countDistinct());
My question is, why I need to select the tables meat and fish first on QueryDSL instead of normal network in SQL ? And because of that invert all the logic, using rightJoin instead of leftJoin and invert the order I used the joins also. I think is a little bit confusing when we are thinking in the SQL query to do it.