Skip to content
Advertisement

Efficient way to join multiple columns to the same column? – SQL

I have a bunch of tables combined together, which each have a column containing some form of user_id. This leads to 12 user_id columns in total.

I want to join each of these user_id columns with a user_id column in a mapping table in order to retrieve the username for each of these user ids.

So (assuming I have 5 user id columns),

Input:

Output:

My code looks something like:

I’m realizing this is extremely inefficient, especially for 12 columns which would mean 12 JOINs. Is there a better or faster way to do this? Thanks!

Advertisement

Answer

You might find it easier to use a correlated subquery for each username, especially where you have to implement many columns as it’s easier to cut n paste!

Something like:

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