Lesson 2 Join.pptx
Lesson 2 Join.pptx
Lesson 2
SQL
The JOIN clause allows you to combine the data from 2 or more tables into one
result set. As we will be selecting from multiple columns, we need to include the
list of the columns we want to choose data from after the FROM clause is
separated by a comma.
In this chapter, we will go over the following JOIN types:
• CROSS Join
• INNER Join
• LEFT Join
• RIGHT Join
Before we get started, let's create a new database and two tables that we are going
to work with:
MySQL JOINS
• We are going to call the database demo_joins:
• Then, the first table will be called users, and it will only
have two columns: id and username:
MySQL JOINS
• Then, let's create a second table called posts, and to keep things
simple, we will have three two columns: id, user_id and title:
We specify 123 as the user ID, but we don't have such a user in our
users table.
Now, if you were to run the LEFT outer join, you would not see the
post as it has a null value for the corresponding users table.
But if you were to run a RIGHT outer join, you would see the post
but not the greisi user as it does not have any posts:
RIGHT JOINS
OUTPUT:
JOIN TABLE
Joins can also be limited with WHERE conditions. For instance, in the
preceding example, if we wanted to join the tables and then restrict to only
username bobby.
The Impact of Condition in JOIN vs. WHERE Clauses
The placement of conditions within a SQL query, specifically in the JOIN vs.
the WHERE clause, can yield different results.
Take a look at the following example, which retrieves POSTS containing the
word "SQL" along with their associated user data:
The Impact of Condition in JOIN vs. WHERE Clauses
However, by shifting the condition to the JOIN clause, all users are displayed,
but only posts with titles containing "SQL" are included:
MySQL JOIN EXAMPLE