Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performing Inner Join for Multiple Columns in the Same Table

I have a scenario which I'm a bit stuck on. Let's say I have a survey about colors, and I have one table for the color data, and another for people's answers.

tbColors

color_code , color_name      1     , 'blue'      2     , 'green'      3     , 'yellow'      4     , 'red' 

tbAnswers

answer_id  ,  favorite_color   ,   least_favorite_color   ,  color_im_allergic_to     1      ,         1          ,         2                            3       2      ,         3          ,         1                            4     3      ,         1          ,         1                            2     4      ,         2          ,         3                            4 

For display I want to write a SELECT that presents the answers table but using the color_name column from tbColors.

I understand the "most stupid" way to do it: naming tbColors three times in the FROM section, using a different alias for each column to replace.

How would a non-stupid way look?

like image 415
Frankie Simon Avatar asked May 09 '10 16:05

Frankie Simon


People also ask

Can you inner join on multiple columns?

Yes: You can use Inner Join to join on multiple columns.

How do I join two different columns in the same table in SQL?

The following example shows how to concatenate three different columns: (SELECT id, email1 AS email FROM customer) UNION (SELECT id, email2 AS email FROM customer) UNION (SELECT id, email3 AS email FROM customer) ORDER BY id, email; As you can see, it's important that all the queries return the same columns.

Can we apply inner join on same table?

The self-join is a special kind of joins that allow you to join a table to itself using either LEFT JOIN or INNER JOIN clause. You use self-join to create a result set that joins the rows with the other rows within the same table.

How do I join 3 columns in SQL?

If you'd like to get data stored in tables joined by a compound key that's a primary key in one table and a foreign key in another table, simply use a join condition on multiple columns. In one joined table (in our example, enrollment ), we have a primary key built from two columns ( student_id and course_code ).


1 Answers

This seems like the way to go:

SELECT   A.answer_id   ,C1.color_name AS favorite_color_name   ,C2.color_name AS least_favorite_color_name   ,C3.color_name AS color_im_allergic_to_name FROM tbAnswers AS A INNER JOIN tbColors AS C1   ON A.favorite_color = C1.color_code INNER JOIN tbColors AS C2   ON A.least_favorite_color = C2.color_code INNER JOIN tbColors AS C3   ON A.color_im_allergic_to = C3.color_code 

Rather than "stupid", I'd venture that this is a pretty standard query. This also presumes that all columns will have a valid value. Otherwise, replace all INNER JOINs with LEFT JOINs

like image 115
BradBrening Avatar answered Sep 22 '22 08:09

BradBrening