Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HQL nested subqueries

I have such domain: Country has cities, city has offices, offices has services. I need to find all countries with offices which provide specified service id. My current version is:

SELECT c FROM Country c 
WHERE EXISTS(
             SELECT ct FROM c.cities ct 
             WHERE EXISTS(
                          SELECT o FROM ct.offices o 
                          WHERE EXISTS(
                                       SELECT s.id FROM o.services s 
                                       WHERE s.id = :id
                                      )
                         ) 
            )

So, I'm new to HQL. What is best way to this? Is my version Ok? I was thinking about SELECT DISTINCT with LEFT JOIN too.

like image 556
xander27 Avatar asked Mar 20 '26 06:03

xander27


1 Answers

I don't think there is anything wrong with your query, but this might be more readable.

SELECT c FROM Country
WHERE EXISTS (
    SELECT s.id FROM
    c.cities ct
    JOIN ct.offices o
    JOIN o.services s
    WHERE s.id = :id
)
like image 137
Glenn Lane Avatar answered Mar 21 '26 20:03

Glenn Lane



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!