I have a courier_routes table which has two foreign keys to a locations table. The columns in the courier_routes table are start_location_id and end_location_id. (I'm using Oracle)
I want to find the all the distinct locations that the courier has been to in the courier_routes table.
Consider this example
|id |start_location_id| end_location_id|...
|1|1|2|
|2|1|3|
|3|4|5|
|4|2|1|
I want to get back ids 1 2 3 4 5
My SQL that works is
SELECT loc FROM (
SELECT start_location_id AS loc FROM courier_routes
UNION
SELECT end_location_id AS loc FROM courier_routes);
I want to translate this into JPA. Hibernate does not support unions so I thought about doing sub queries. The problem with this is that it could affect performance.
I was thinking of something like (pseudo code...)
SELECT id FROM locations where id in (
(SELECT start_location_id FROM courier_routes)
OR
(SELECT end_location_id FROM courier_routes));
Is there an easier way? This table will get big so I really dont want to use sub-queries.
Should I just do a union in java by adding two separate query results into a set?
Thanks
You can do a join on the two columns in HQL :
SELECT distinct loc.id FROM locations loc, courier_routes c
where loc.id=c.start_location_id OR c.id=c.end_location_id
Hope this helps!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.