【发布时间】:2020-11-22 03:42:08
【问题描述】:
我对以下数据库实体关系有点挣扎:
我想创建一个查询,在其中获取作为所有者的用户的所有事件 (item-user_id) 或参与者 (participant-user_id)
我回到原生查询,因为它们更容易尝试。 但是注册和参与者之间的一对多关系对我不起作用。
在where 子句和unions 中尝试了joins、sub-queries .. 但到目前为止没有任何效果。
以下是一些示例:
第一个有联合的 -> 但它返回的结果不正确
select e.id, e.has_location, e.has_registration, e.parent_id, e.published, e._end, e.start
from event e
inner join item i on e.id = i.id
where i.user_id = 2 and start >= '2020-08-01T00:00:00'
union
select e.id, e.has_location, e.has_registration, e.parent_id, e.published, e._end, e.start
from event e
inner join registration_participants r on r.registration_id = e.id
inner join participant p on r.participants_id = p.id
where p.user_id = 2
and e.has_registration
and p.status != 'CANCELED'
and start >= '2020-08-01T00:00:00'
order by start;
比带有一些子查询的那个 -> 但结果也是错误的
select e.id, e.has_location, e.has_registration, e.parent_id,
e.published, e.start, e._end from event e
inner join item i on e.id = i.id where i.user_id = 2 or (select p.user_id
from participant p
inner join registration_participants r on e.id = r.registration_id
where r.participants_id = p.id
and p.status != 'CANCELED'
) = 2 order by e.start
【问题讨论】:
-
样本数据和期望的结果真的很有帮助。你的数据模型和问题很难理解。随后的查询有额外的条件和相当奇怪的连接条件。
-
您在示例查询中有
registration_participants表,但在图表上。请提供完整图片以获得更好的帮助 -
我添加了一张更具体的图片,也带有正确的表名。还要提一下,即使像@GordonLinoff 指出的那样非常不规则,我还是通过 konvetion 将这些东西放在一起,这意味着注册、事件和项目的 id 总是(由项目 id 生成的值给出)
标签: sql postgresql jpa spring-data-jpa