Get All Customers And Orders
What is the basic query to link all the tables? We basically want to get all customers and all their orders.
select co.id as orderId, co.orderDate, c.name, c.city, c.state, p.description, p.price from customers c, customerOrders co, orderLineItems olm, products p where c.id = co.customerId and co.id = olm.orderId and olm.productId = p.id order by co.orderDate;
We can break this query out like:
select
co.id as orderId,
co.orderDate,
c.name,
c.city,
c.state,
p.description,
p.price
from
customers c,
customerOrders co,
orderLineItems olm,
products p
where
c.id = co.customerId
and
co.id = olm.orderId
and
olm.productId = p.id
order by
co.orderDate;
And our output from this query:
+---------+------------+-------------------+-------------+-------+-------------------------------------------+-------+
| orderId | orderDate | name | city | state | description | price |
+---------+------------+-------------------+-------------+-------+-------------------------------------------+-------+
| 1 | 2020-01-01 | Crab Rock | Los Angeles | CA | Large Floppy Toothbrush With Suds | 19.95 |
| 1 | 2020-01-01 | Crab Rock | Los Angeles | CA | Hand Cuffs | 10.88 |
| 2 | 2020-01-02 | Crab Rock | Los Angeles | CA | Vibra-Glove Trick Buzzin Glove | 29.95 |
| 3 | 2020-01-10 | Gib Bigger | Camden | WA | Vibra-Glove Trick Buzzin Glove | 29.95 |
| 3 | 2020-01-10 | Gib Bigger | Camden | WA | Sense-attentive Electrocute Your Friends! | 49.95 |
| 3 | 2020-01-10 | Gib Bigger | Camden | WA | Hand Cuffs | 10.88 |
| 4 | 2020-02-07 | Donkey Woman | Visia | OR | Large Floppy Clown Shoes | 19.95 |
| 5 | 2020-03-01 | InfiniteBliss6969 | Los Angeles | CA | Blow Up Balloon Animal Balloons | 8.95 |
+---------+------------+-------------------+-------------+-------+-------------------------------------------+-------+
8 rows in set (0.01 sec)
Each row that is retrieved is one line item of a customer order. For example, Gib Bigger has three different products that they purchased for one order.