forked from Jeanhwea/mysql-crash-course
-
Notifications
You must be signed in to change notification settings - Fork 0
/
17-combining-queries.sql
95 lines (90 loc) · 2.87 KB
/
17-combining-queries.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
85
86
87
88
89
90
91
92
93
94
95
-- 第17章 组合查询
-- use UNION
SELECT vend_id, prod_id, prod_price
FROM products
WHERE prod_price <= 5;
-- +---------+---------+------------+
-- | vend_id | prod_id | prod_price |
-- +---------+---------+------------+
-- | 1003 | FC | 2.50 |
-- | 1002 | FU1 | 3.42 |
-- | 1003 | SLING | 4.49 |
-- | 1003 | TNT1 | 2.50 |
-- +---------+---------+------------+
SELECT vend_id, prod_id, prod_price
FROM products
WHERE vend_id IN (1001, 1002);
-- +---------+---------+------------+
-- | vend_id | prod_id | prod_price |
-- +---------+---------+------------+
-- | 1001 | ANV01 | 5.99 |
-- | 1001 | ANV02 | 9.99 |
-- | 1001 | ANV03 | 14.99 |
-- | 1002 | FU1 | 3.42 |
-- | 1002 | OL1 | 8.99 |
-- +---------+---------+------------+
SELECT vend_id, prod_id, prod_price
FROM products
WHERE prod_price <= 5
UNION
SELECT vend_id, prod_id, prod_price
FROM products
WHERE vend_id IN (1001, 1002);
-- +---------+---------+------------+
-- | vend_id | prod_id | prod_price |
-- +---------+---------+------------+
-- | 1003 | FC | 2.50 |
-- | 1002 | FU1 | 3.42 |
-- | 1003 | SLING | 4.49 |
-- | 1003 | TNT1 | 2.50 |
-- | 1001 | ANV01 | 5.99 |
-- | 1001 | ANV02 | 9.99 |
-- | 1001 | ANV03 | 14.99 |
-- | 1002 | OL1 | 8.99 |
-- +---------+---------+------------+
SELECT vend_id, prod_id, prod_price
FROM products
WHERE prod_price <= 5
OR vend_id IN (1001, 1002);
-- use UNION ALL
SELECT vend_id, prod_id, prod_price
FROM products
WHERE prod_price <= 5
UNION ALL
SELECT vend_id, prod_id, prod_price
FROM products
WHERE vend_id IN (1001, 1002);
-- +---------+---------+------------+
-- | vend_id | prod_id | prod_price |
-- +---------+---------+------------+
-- | 1003 | FC | 2.50 |
-- | 1002 | FU1 | 3.42 |
-- | 1003 | SLING | 4.49 |
-- | 1003 | TNT1 | 2.50 |
-- | 1001 | ANV01 | 5.99 |
-- | 1001 | ANV02 | 9.99 |
-- | 1001 | ANV03 | 14.99 |
-- | 1002 | FU1 | 3.42 |
-- | 1002 | OL1 | 8.99 |
-- +---------+---------+------------+
-- sort UNION result
SELECT vend_id, prod_id, prod_price
FROM products
WHERE prod_price <= 5
UNION
SELECT vend_id, prod_id, prod_price
FROM products
WHERE vend_id IN (1001, 1002)
ORDER BY vend_id, prod_id;
-- +---------+---------+------------+
-- | vend_id | prod_id | prod_price |
-- +---------+---------+------------+
-- | 1001 | ANV01 | 5.99 |
-- | 1001 | ANV02 | 9.99 |
-- | 1001 | ANV03 | 14.99 |
-- | 1002 | FU1 | 3.42 |
-- | 1002 | OL1 | 8.99 |
-- | 1003 | FC | 2.50 |
-- | 1003 | SLING | 4.49 |
-- | 1003 | TNT1 | 2.50 |
-- +---------+---------+------------+