HQL:使用嵌套选择加入

时间:2014-02-28 21:33:16

标签: sql hql

我正在尝试使用HQL实现此查询:

SELECT * 
FROM Gift g 
LEFT OUTER JOIN (SELECT det.GiftId FROM ItemDetails det WHERE det.Active=1) r1 ON g.GiftId=r1.GiftId 
WHERE r1.GiftId IS null

这个查询给了我在SQL Server中需要的东西,但我需要它在HQL中工作。我试过这个:

SELECT distinct g
FROM (SELECT det.gift FROM ItemDetails det WHERE det.active=1) as r
RIGHT OUTER JOIN r.gift g
WHERE r.gift IS null

GiftId是ItemDetails中的一个外键,它引用Gift中的一行。我认为这不起作用,因为嵌套查询在FROM子句中,但我不知道如何重新编写它。有什么建议?

编辑:最终工作版..

   SELECT distinct g
   FROM Gift g 
   WHERE NOT EXISTS (from ItemDetails det where det.active=1 and det.gift=g.id)

1 个答案:

答案 0 :(得分:1)

这个版本有用吗?

SELECT g.*
FROM Gift g
WHERE not exists (select 1
                  from ItemDetails det
                  where det.Active = 1 and
                        det.GiftId = g.GiftId
                 );

您也可以left outer join

执行此操作
SELECT g.* 
FROM Gift g LEFT OUTER JOIN
     ItemDetails det 
     on det.Active = 1 and g.GiftId = r1.GiftId 
WHERE det.GiftId IS null;

您不需要子查询,因为您可以将过滤条件移动到on子句中。

相关问题