【问题标题】:SQL select data based on a one to many relationSQL 基于一对多关系选择数据
【发布时间】:2020-11-22 03:42:08
【问题描述】:

我对以下数据库实体关系有点挣扎:

我想创建一个查询,在其中获取作为所有者的用户的所有事件 (item-user_id) 或参与者 (participant-user_id)

我回到原生查询,因为它们更容易尝试。 但是注册和参与者之间的一对多关系对我不起作用。

where 子句和unions 中尝试了joinssub-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


【解决方案1】:

一种方法使用exists

select e.*
from event e
where exists (select 1 from item i where i.id = e.id and i.user_id = 2) or
      exists (select 1 from registration r where r.registration_id = e.id and r.participant = 2);

我不确定还有哪些其他条件(例如日期和状态)。它们没有在问题或数据模型中描述。

也就是说,itemevent 之间的join 条件似乎非常不规则,它位于名为id 的列上。我希望它使用event_iditem_id。如果您遇到问题,我怀疑它涉及连接条件。

【讨论】:

  • 感谢您的快速回复.. 我知道使用相同的 id 是非常不规则的,试图通过将控制从 JPA/Hibernate 移开来更容易访问数据..
  • 我能够使用该答案以及对 jpa 内容的一些细微修改来摆脱 registration_participants 我从 @ElementCollection 移动到 @OneToMany@JoinColumn
猜你喜欢
  • 2021-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-11
  • 1970-01-01
  • 2013-03-08
  • 1970-01-01
相关资源
最近更新 更多