-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLeft Joins
50 lines (40 loc) · 1.66 KB
/
Left Joins
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
SQL lets us do this through a command called LEFT JOIN.
A left join will keep all rows from the first table, regardless of whether there is a matching row in the second table.
Example:
The first and last rows have matching values of c2. The middle rows do not match.
The final result will keep all rows of the first table but will omit the un-matched row from the second table.
This animation represents a table operation produced by the following command:
SELECT *
FROM table1
LEFT JOIN table2
ON table1.c2 = table2.c2;
BREAKDOWN OF ABOVE:
The first line selects all columns from both tables.
The second line selects table1 (the “left” table).
The third line performs a LEFT JOIN on table2 (the “right” table).
The fourth line tells SQL how to perform the join (by looking for matching values in column c2).
EXAMPLE:
Suppose we want to know how many users subscribe to the print newspaper, but not to the online.
Start by performing a left join of newspaper table and online table on their id columns and selecting all columns.
CODE:
SELECT *
FROM newspaper
LEFT JOIN online
ON newspaper.id = online.id;
EXAMPLE:
In order to find which users do not subscribe to the online edition, we need to add a WHERE clause.
Add a second query after your first one that adds the following WHERE clause and condition:
WHERE online.id IS NULL
This will select rows where there was no corresponding row from the online table.
CODE:
SELECT *
FROM newspaper
LEFT JOIN online
ON newspaper.id = online.id
WHERE online.id IS NULL;
//If we want count of users not subscribed to online edition//
SELECT COUNT(*)
FROM newspaper
LEFT JOIN online
ON newspaper.id = online.id
WHERE online.id IS NULL;