r/SQL•
Istdas

Create an edge list via SQL

PostgreSQL

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

I am trying to build an undirected graph with edges representing that an artist has performed at the same event as another artist. The trivial solution using python is taking a lot of time to process with 5k artists and 17k records in artist_event. I wanted to see if there was a way to use SQL to create an edge list table that I can access with pandas and then create a graph using networkx.from_pandas_edgelist. My assumption is that this would be a faster solution than attempting to iterate through artists via python lists (but let me know if I'm mistaken.)

Here are my tables

*artist*
id
name

*event*
id
date

*artist_event*
artist_id
event_id

I am looking to create a query that results in a table like

*source_artist*     *target_artist*
      1                            2
      1                            5
      1                            7
      2                            1
      2                            25

etc. with the left column iterating through every artist_id and the right column representing every artist that has performed with them in any of their events.

Some preliminary research leads me to believe I will need to use WITH RECURSIVE but I'm still a noobie with SQL so I can't figure out how to properly set things up. Any help and direction would be really appreciated!

Posted Jun 8, 2022, 3:14 PM UTC

13
r3pr0b8GROUP_CONCAT is da bomb•

with the left column iterating through every artist_id and the right column representing every artist that has performed with them in any of their events.

SELECT artist.id         AS source_artist
     , target.artist_id  AS target_artist
  FROM artist
INNER
  JOIN artist_event
    ON artist_event.artist_id = artist.id
INNER
  JOIN artist_event AS target
    ON target.event_id = artist_event.event_id
   AND target.artist_id <> artist.id
5
IstdasOP•

SELECT artist.id AS source_artist , target.artist_id AS target_artist FROM artist INNER JOIN artist_event ON artist_event.artist_id = artist.id INNER JOIN artist_event AS target ON target.event_id = artist_event.event_id AND target.artist_id <> artist.id

Wow that was fast. Thank you so much!

1
DavidGJohnston•

FROM is your starting point. You basically need one join per edge you want to capture. You know you want to capture pairs of edges (linking them together due to the shared node) thus you need exactly two joins. If you don't know how many joins/edges you would have to traverse to find your other node you would have to use WITH RECURSIVE to traverse the first edge, then the next, as so forth until you find your desired node.

0