You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
CREATETABLEorders
(
id INTPRIMARY KEY AUTO_INCREMENT,
order_date DATE,
amount DECIMAL(8,2),
customer_id INT,
FOREIGN KEY (customer_id) REFERENCES customers(id) ON DELETE CASCADE-- customer 가 사라지는 경우, 해당 customer 의 id 를 foreign key 로 가지는 order row 함께 제거.
)
INSERT INTO orders(order_date, amount, customer_id)
VALUES('1999-04-11', 450.25, 10);
-- invalid foreign key error!-- cannot add or update a child row; a foreign key constraint fails -- (FOREIGN KEY ('customer_id') REFERENCES 'customers' ('id'))
-- SELECT 'Boy George's ordersSELECT id FROM customers WHERE first_name='Boy'and last_name='George';
SELECT*FROM orders WHERE customer_id=1;
-- using one line SELECT*FROM orders WHERE customer_id = (SELECT id FROM customers WHERE last_name='George');
SELECT*FROM customers, orders;
-- CrossJoin: Combination of customers X orders (meaningless data)
-- select all customers, orders data only if matched customer_id existSELECT*FROM customers
JOIN orders
ONcustomers.id=orders.customer_id;
-- print specific infos from matched dataSELECTcustomers.id, first_name, last_name, order_date, amount FROM customers
JOIN orders
ONcustomers.id=orders.customer_id;
-- print name and sum of amount of customers with ordersSELECT first_name, last_name, SUM(amount) as total FROM customers
JOIN orders
ONcustomers.id=orders.customer_idGROUP BY first_name, last_name
ORDER BY total;
-- select all data (of customers) even if there's no matched data from ordersSELECT first_name, last_name, order_date, amount FROM customers
LEFT JOIN orders ONorders.customer_id=customers.id;
-- select sum of customer's order data. SELECT first_name, last_name, IFNULL(SUM(amount), 0) AS money_spent FROM customers
LEFT JOIN orders ONorders.customer_id=customers.idGROUP BY first_name, last_name;