r/SQL•
Istdas

N self joins based on N ids

PostgreSQL

I have three tables representing a many-to-many relationship: artist, event, and artist_event (the junction table).

I am setting up a retool.com app in order to allow folks to query our Postgres database. One thing I am interested in doing is allowing my colleagues to query our event archive by the artists involved. I was able to use your help from my last post to set it up for 2 artists but I need to be able to change the query based on an unknown amount of artists. So if my colleague includes 3 artists then the query needs to result in a table showing events where all 3 artists participated in. If they choose 4 artists it needs to show events where all 4 artists participated, etc.

I have been having trouble finding online resources to get a better idea of working with recursive queries so I haven't been able to figure this one out. Any help would be really appreciated!

For reference, here are my tables:

*artist*
id
name

*event*
id
date

*artist_event*
artist_id
event_id
id

And here is the self-join I wrote that works with 2 artists (I need it to work with N artists based on input from colleagues). The {{ }} notation comes from retool. multiselect_artists.value holds an array of artist_ids. The "!multiselect_artists.value.length" part ensures that the query goes off with all events/artists if the artist field is left blank.

WITH filtered_events AS (select
 event.id as event_id,
 event.date as event_date,
 event.title as event_title,
 event.description as event_description,
 artist_event.artist_id as left_artist,
 target.artist_id as right_artist
from artist
join artist_event
  on artist_event.artist_id=artist.id 
RIGHT join event
  on artist_event.event_id=event.id 
join artist_event as target
  on target.event_id=artist_event.event_id
where 
  (
      ({{!multiselect_artists.value.length}}) 
  OR 
     (artist_event.artist_id=ANY({{multiselect_artists.value}})
      AND 
      target.artist_id=ANY({{multiselect_artists.value}})
      AND
      artist_event.artist_id <> target.artist_id
     )
  )
  AND
  (event.date BETWEEN {{event_date_range.value.start}} AND {{event_date_range.value.end}})
) SELECT DISTINCT ON(event_id) event_id,
  event_date,
  event_title,
  event_type,
  event_description
  FROM filtered_events

Posted Jun 13, 2022, 6:05 PM UTC · edited

12
r3pr0b8GROUP_CONCAT is da bomb•

self-joins are, in my opinion, needlessly complex for this scenario

SELECT event_id
  FROM artist_event
 WHERE artist_id IN ( 3, 6, 9 )
GROUP
    BY event_id
HAVING COUNT(DISTINCT artist_id) = 3

this query gives you the events, so with this as a subquery in the FROM clause, you can join to event to get the event name

3
IstdasOP•

Thank you so much! You're right that my query was way more complicated than necessary. This is such a big help and gives me a better idea of how to formulate my queries going forward!

1