Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join two tables by multiple columns in SQL?

I have two tables named Evaluation and Value.

In both tables, there are four columns. But three of the four are the same. In other words, they both have the CaseNum, FileNum, ActivityNum columns. In addition to those, the Evaluation table has the Grade column, and the Value table has the Score column.

I want to merge the two into one table, joining by CaseNum, FileNum, and ActivityNum, so I have a new table of five columns, including Value and Score.

Can I use INNER JOIN multiple times to do this?

like image 991
JasonSmith Avatar asked Nov 13 '14 19:11

JasonSmith


People also ask

Can you join two tables with multiple columns 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 ).


Video Answer


2 Answers

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

SELECT E.CaseNum, E.FileNum, E.ActivityNum, E.Grade, V.Score from Evaluation E INNER JOIN Value V ON E.CaseNum = V.CaseNum AND     E.FileNum = V.FileNum AND      E.ActivityNum = V.ActivityNum 

Create table

CREATE TABLE MyNewTab(CaseNum int, FileNum int,     ActivityNum int, Grade int, Score varchar(100)) 

Insert values

INSERT INTO MyNewTab Values(CaseNum, FileNum, ActivityNum, Grade, Score) SELECT E.CaseNum, E.FileNum, E.ActivityNum, E.Grade, V.Score from Evaluation E INNER JOIN Value V ON E.CaseNum = V.CaseNum AND     E.FileNum = V.FileNum AND      E.ActivityNum = V.ActivityNum 
like image 110
Ganesh Avatar answered Sep 21 '22 06:09

Ganesh


No, just include the different fields in the "ON" clause of 1 inner join statement:

SELECT * from Evalulation e JOIN Value v ON e.CaseNum = v.CaseNum
    AND e.FileNum = v.FileNum AND e.ActivityNum = v.ActivityNum
like image 27
Barett Avatar answered Sep 20 '22 06:09

Barett