-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCombining tables with SQL
50 lines (38 loc) · 1.74 KB
/
Combining tables with 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
Combining tables manually is time-consuming. Luckily, SQL gives us an easy sequence for this:
// it’s called a JOIN //
Example:
If we want to combine orders and customers, we would type:
SELECT *
FROM orders
JOIN customers
ON orders.customer_id = customers.customer_id;
Let’s break down this command:
The first line selects all columns from our combined table. If we only want to select certain columns, we can specify which ones we want.
The second line specifies the first table that we want to look in, orders
The third line uses JOIN to say that we want to combine information from orders with customers.
The fourth line tells us how to combine the two tables. We want to match orders table’s customer_id column with customers table’s customer_id column.
We use the syntax table_name.column_name to be sure that our requests for columns are unambiguous.
In our example, we use this syntax in the ON statement
EXAMPLE:
Instead of selecting all the columns using *, if we only wanted to select orders table’s order_id column and customers table’s customer_name column, we could use the following query:
SELECT orders.order_id,
customers.customer_name
FROM orders
JOIN customers
ON orders.customer_id = customers.customer_id;
Example:
Join orders table and subscriptions table and select all columns.
Make sure to join on the subscription_id column.
CODE:
SELECT *
FROM orders
JOIN subscriptions
ON orders.subscription_id = subscriptions.subscription_id;
Example II
Add a second query after your first one that only selects rows from the join where description is equal to ‘Fashion Magazine’.
CODE:
SELECT *
FROM orders
JOIN subscriptions
ON orders.subscription_id = subscriptions.subscription_id
WHERE subscriptions.description = 'Fashion Magazine';