首页 > 解决方案 > SQL 基于一对多关系选择数据

问题描述

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

在此处输入图像描述

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

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

尝试过joinssub-querieswhere子句中和unions.. 但到目前为止没有任何效果。这里有些例子:

第一个带有 union -> 但它返回的结果不正确

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

标签: sqlpostgresqljpaspring-data-jpa

解决方案


一种方法使用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);

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

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


推荐阅读