-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathjoins.sql
84 lines (70 loc) · 1.64 KB
/
joins.sql
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/* Select all columns in the company_division table to review contents of the table */
select
*
from
company_divisions;
/* And get a count to understand the size of the table */
select
count(*)
from
company_divisions;
/* Join staff and department. If the staff department is not found in */
/* company_divisions, then no row will be returned. */
select
s.last_name, s.department, cd.company_division
from
staff s
join
company_divisions cd
on
s.department = cd.department;
/* The previous query did not return 1,000 rows. What rows are missing? */
select distinct
department
from
staff
where
department not in
(select
department
from
company_divisions);
/* Use an outer join to return all rows, even it a corresponding row in */
/* company_divsion does not exist. */
select
s.last_name, s.department, cd.company_division
from
staff s
left join
company_divisions cd
on
s.department = cd.department;
/* This will generate an ERROR */
/* Perform 3 table join without alias to generate error */
/* Since department occurs in both staff and company_divisions */
/* we need to use an alias to specify which table should be use */
select
last_name, department, company_division, company_region
from
staff s
join
company_divisions cd
on
s.department = cd.department
join
company_regions cr
on
s.region_id = cr.region_id;
/* ... now wiht alias, and there is no error */
select
s.last_name, s.department, cd.company_division, cr.company_region
from
staff s
join
company_divisions cd
on
s.department = cd.department
join
company_regions cr
on
s.region_id = cr.region_id;