SQL has the flexibility to join tables on any column(s) using any predicate (=, >, < ). Most of the time the join will use equality between a primary and foreign key. Think of example where joining on something other than keys would be needed. Write the query both as an English sentence and in SQL. If you can't think of your own example, search the textbook or internet for an example.
I think one way to look at this in English would be sales in a store. For example, we want a list of the total stock of a product along with the total number of that product the store has sold.In SQL, I think it would look like this:
SELECT p.product_name
SUM(p.quantity) AS current_stock
SUM(s.quantity AS total_sold
FROM products AS p
LEFT JOIN sales AS s ON p.product_name = s.product_name
WHERE p.product_name = 'apples'
GROUP BY p.product_name;
No comments:
Post a Comment