Skip to content
Advertisement

SQL select data based on a one to many relation

I struggle a little with the following database entity relations:

enter image description here

I would like to create a query where I get all events for a user that is either the owner (item-user_id) or a participant (participant-user_id)

I got back to native queries, cause they are more easy to try out. But the one to many relation between the registration and the participant won’t work for me.

Tried joins, sub-queries in the where clause and unions .. but nothing worked so far. Here are some examples:

First the one with the union -> but it returns not the correct result

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;

than the one with some sub query -> but result is also wrong

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

Advertisement

Answer

One method uses 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);

I am not sure what other conditions (such as on date and status are). They are not described in the question or the data model.

That said, it seems highly irregular that the join condition between item and event would be on a column called id. I would expect it to be using either event_id or item_id. If you are having a problem, I suspect it involves the join conditions.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement