Well done! When writing an INSERT
statement, you can also refer to other tables by using a JOIN
in a SELECT
clause.
The store staff would like to add new tables to help them prepare detailed sales reports. They have created a table named sales_report
that combines details about individual purchases: purchase_id
, total_price
, order_date
, and quantity
. Additionally, the table also includes details about the product bought in this purchase: product_name
(i.e., name from the product
table). To insert data into this table, you can use the following statement:
INSERT INTO sales_report
SELECT
pu.id,
pr.name,
pu.total_price,
pu.order_date,
pu.quantity
FROM purchase pu
INNER JOIN product pr
ON pu.product_id = pr.id
WHERE is_completed = true
AND pu.order_date <= '2016-12-31';
The SELECT
query chooses important product details for each purchase, making it easy to create sales reports. The query joins data from the product
and purchase
tables and puts it into the sales_report
table.