我有2个表(实体),一个人实体和一个度假实体。一个人可以有很多假期。
我要做的是以下查询:
选择所有人的期间!但是对于有假期的人,我想要取出所有有条件的人休假,以免说startDate
介于某事之间。
为了清楚,无论假期的限制我仍然想要所有的人。这是我当前的HQL查询:
select distinct p
from Person as p
left join fetch p.vacations as v
where v.startDate between '2011-07-01' and '2011-07-30'
它的问题在于它限制了我的人只返回那些有尊重条件的假期的人....有人可以帮忙吗?
如果有人可以在原生SQL中告诉我这个问题我没有问题
更新感谢@Quasdunk解决了本机SQL:
SELECT *
FROM person as p
LEFT JOIN
(SELECT * FROM vacation
WHERE startDate BETWEEN '2011-08-01' AND '2011-08-30') as v ON v.person_id = p.id
我的新问题是如何将其转换为HQL查询,以便我可以获取每个人的假期,以及不同的人(条件保持不变)。
答案 0 :(得分:1)
在本机SQL中,这将是:
SELECT *
FROM person
LEFT JOIN (SELECT *
FROM vacations
WHERE startDate BETWEEN '2011-07-01' AND '2011-07-30')
未经测试,但你明白了这一点:)
答案 1 :(得分:0)
尝试以下方法,
select p.*, v.* from PERSON p LEFT JOIN VACATION v
on (p.id = v.p_id)
where v.startDate between '2011-07-21' and '2011-07-22'
希望这适合你。
答案 2 :(得分:0)
您可能希望使用函数来实现它:
select p from Person p
where p.vacations.size = 0
or (minelement(p.vacations) > '2011-07-01'
and
maxelement(p.vacations) < '2011-07-30')
这些日期实际上可能是日期类型。取决于类型。
尝试
select p from Person p
where p.vacations.size = 0
or (p.vacations.startDate > '2011-07-01'
and
p.vacations.endDate < '2011-07-30')
您还应该查看here
答案 3 :(得分:0)
在plain(My)SQL中,它看起来像这样:
select distinct p.* from person p
left join vacations v on p.id = v.person_id
where v.id is null or.v.start_date between '2011-07-01' and '2011-07-30'
在HQL中,这可能是(未经测试)
select distinct p from Person as p
left join fetch p.vacations as v
where v.id is null or v.startDate between '2011-07-01' and '2011-07-30'
或者(我不确定这是否有效)
select distinct p from Person as p
left join fetch p.vacations as v
where v is null or v.startDate between '2011-07-01' and '2011-07-30'