-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJoins & Union
64 lines (53 loc) · 1.92 KB
/
Joins & Union
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
# Join statement
# Inner joins, Full/Left/Right outer joins
# Join/Innner Join
SELECT *
FROM EmployeeDemographics
JOIN EmployeeSalary
ON EmployeeDemographics.EmployeeID = EmployeeSalary.EmployeeID
# Full Outer Join
SELECT *
FROM EmployeeDemographics
FULL OUTER JOIN EmployeeSalary
ON EmployeeDemographics.EmployeeID = EmployeeSalary.EmployeeID
# Upon research, MYSQL doesn't support "Full Outer Join". In order to do a Full Outer Join, a combination of Left & Right Join would be needed
# The query below will returns data based on the JOIN EmployeeID, without returning any duplicates.
SELECT *
FROM EmployeeDemographics
LEFT JOIN EmployeeSalary ON EmployeeDemographics.EmployeeID = EmployeeSalary.EmployeeID
UNION ALL
SELECT *
FROM EmployeeDemographics
RIGHT JOIN EmployeeSalary ON EmployeeDemographics.EmployeeID = EmployeeSalary.EmployeeID
# The query below using will return duplicate rows
SELECT *
FROM EmployeeDemographics
LEFT JOIN EmployeeSalary ON EmployeeDemographics.EmployeeID = EmployeeSalary.EmployeeID
UNION ALL
SELECT *
FROM EmployeeDemographics
RIGHT JOIN EmployeeSalary ON EmployeeDemographics.EmployeeID = EmployeeSalary.EmployeeID
WHERE EmployeeDemographics.EmployeeID IS NULL
# Left Join
SELECT *
FROM EmployeeDemographics
LEFT JOIN EmployeeSalary
ON EmployeeDemographics.EmployeeID = EmployeeSalary.EmployeeID
# Right Join
SELECT *
FROM EmployeeDemographics
RIGHT JOIN EmployeeSalary
ON EmployeeDemographics.EmployeeID = EmployeeSalary.EmployeeID
#Difference between Join & Union. Join merges tables based on a common column. Union lets you select all data in both tables and put it into one output.
# Union combines data in both tables, while removing duplicates.
SELECT *
FROM EmployeeDemographics
UNION
SELECT *
FROM WareHouseEmployeeDemographics
# Union All combines data from both tables while still showing duplicates.
SELECT *
FROM EmployeeDemographics
UNION ALL
SELECT *
FROM WareHouseEmployeeDemographics