繁体   English   中英

在JPA中区分多个列

[英]Distinct Over multiple columns in JPA

我有一个courier_routes表,其中有两个到locations表的外键。 courier_routes表中的列是start_location_id和end_location_id。 (我正在使用Oracle)

我想在courier_routes表中找到该快递员去过的所有不同位置。

考虑这个例子

|id |start_location_id| end_location_id|...
|1|1|2|
|2|1|3|
|3|4|5|
|4|2|1|

我想找回ID 1 2 3 4 5

我的SQL有效

SELECT loc FROM (
SELECT start_location_id AS loc FROM courier_routes 
UNION
SELECT end_location_id AS loc FROM courier_routes);

我想将其翻译成JPA。 Hibernate不支持联合,所以我考虑了做子查询。 问题在于这可能会影响性能。

我在想类似的东西(伪代码...)

SELECT id FROM locations where id in (
    (SELECT start_location_id FROM courier_routes) 
       OR
    (SELECT end_location_id FROM courier_routes));

有更容易的方法吗? 这个表会变大,所以我真的不想使用子查询。

我是否应该在Java中通过将两个单独的查询结果添加到集合中来进行并集?

谢谢

您可以在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

希望这可以帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM