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

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

Advertisement

Answer

One method uses exists:

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