【问题标题】:Hibernate: Joining CriteriaHibernate:加入标准
【发布时间】:2012-08-29 09:48:13
【问题描述】:

您好,我需要使用 Criteria 执行以下操作

Select * from product pd, (Select productID pd1 from ... where ...) tpd1, 
(Select productID pd2 from ... where ...) tpd2
where pd.productID = tpd1.pd1 and pd.productID = tpd1.pd2

请问可以吗?

原来的 SQL 使用的是 IN 条件

Select * from product pd where productID in (Select productID pd1 from ... where ...) and 
productID in (Select productID pd2 from ... where ...) 

但是得到结果的时间太长了,使用join SQL语句我能够更快地得到我的结果。

有什么帮助吗?

【问题讨论】:

  • 请发布原始查询的解释计划。

标签: java oracle hibernate


【解决方案1】:

鉴于您使用的是 Hibernate,您可能需要执行以下操作,如果预期匹配的数量相对较少,这应该可以正常工作:

select *
from   product pd
where  pd.productID in
   (select productID
    from   product pd2
    join   tpd1 on (pd2.productID = tpd1.pd1)
    join   tpd2 on (pd2.productID = tpd2.pd2)
    where  tpd1....
    and    tpd2....
   );

我假设product.productID 上有一个唯一索引。

或者,您可以尝试 EXISTS 公式,该公式可能会或可能不会比您的原始查询更好:

select *
from   product pd
where  EXISTS
   (select null from tpd1 where pd.productID = tpd1.pd1 and ...)
and    EXISTS
   (select null from tpd2 where pd.productID = tpd2.pd2 and ...)
;

【讨论】:

  • 我目前是您建议的具有休眠标准的解决方案,但由于某些 select 语句已经过时,因此非常滞后。我尝试使用 SQL 优化器,它建议使用连接表。不会加载您建议的解决方案的 OUTLINER 输入,但会加载连接表查询。原因之一是返回的数据量很大。
  • 您确实需要为您的查询发布解释计划 - 更好的是,对于所有建议的查询。没有计划,我们只能猜测。
猜你喜欢
  • 2014-12-05
  • 2019-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-25
  • 1970-01-01
  • 1970-01-01
  • 2011-10-17
相关资源
最近更新 更多