I am SO confused on the concept of "JOINS" (Inner, Outer, Right, Left, etc)

Think of it like this. When you join something you're adding.

So take this set of data:

Month Year TeamName TeamID
1 2016 Lions x
1 2016 Tigers y
1 2016 Bears z
2 2016 Lions x
2 2016 Tigers y
2 2016 Bears z

Which you get from this code:

select
distinct
    month
    , year
    , teamname
from schedules
where
    month in ('1', '2')
    and year = '2016'

Basically its giving you all the teams that played a game in January or February in 2016, and the schedules table only stores the games.

But what if you want to know the results of the games and that information is in another table that looks like this:

Month Year TeamID Score
2 2016 z 42

How can you connect (or join) these two tables to get the teamname & score to appear together? The "key" is the TeamID. So you could do this manually such as:

select
distinct
    month
    , year
    , teamname
    , score
from scores
where
    month in ('1', '2')
    and year = '2016'
    and teamid = 'z'

Then you could copy everything to Excel and manually copy each corresponding cell to fill in the scores for each game, right?

A simpler way looks like this:

select
distinct
    a.month
    , a.year
    , a.teamname
    , b.score
from schedules
inner join scores b on b.teamid = a.teamid
where
    month in ('1', '2')
    and year = '2016'

It takes the two tables and "smooshes" them together, and each join behaves a little differently.

  1. INNER JOIN: When you only want whats in both places.
  2. LEFT JOIN: When you want everything from the first place even if its not in the second place, but you want whats in the second place if it is there.
  3. RIGHT JOIN: Same as a LEFT
  4. FULL OUTER JOIN: I want both of everything.
/r/SQL Thread Parent