sql - SQL 基于一对多关系选择数据
问题描述
我对以下数据库实体关系有些挣扎:
我想创建一个查询,在其中获取所有者(item-user_id)或参与者(participant-user_id)的用户的所有事件
我回到原生查询,因为它们更容易尝试。但是注册和参与者之间的一对多关系对我不起作用。
尝试过joins
,sub-queries
在where
子句中和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
解决方案
一种方法使用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 或. 如果您遇到问题,我怀疑它涉及连接条件。join
item
event
id
event_id
item_id
推荐阅读
- python - ValueError:未知的损失函数:使用我的自定义损失函数加载模型时的focal_loss_fixed
- javascript - 从对象数组构建列表未捕获类型错误:无法读取 null 的属性“appendChild”
- spring-data-jpa - Spring JPA Entities:Ignite错误、LAZY fetching、too-m相关问题,最小化数据库使用和使用Ignite
- python - 在不同版本中使用 pyplot 总是会产生“TypeError: 'numpy.float64' object is not callable”
- c++ - C++ 程序给出了太多参数警告
- php - Memcached 无论如何都会在 300 秒后过期
- c++ - 我需要声明一个包含整数向量的 4x4 矩阵
- reactjs - React 应用程序突然停止(在开发和生产中)
- mongodb - 仅当文档在 MongoDB 中更新时才更新字段
- c# - HttpResponse 设置 Cookie