์ํ(products) ํ
์ด๋ธ
id | name | price |
---|
1 | ๋ฉํฑ | 1200 |
2 | ํธ๋ํฐ | 800 |
3 | ํ๋ธ๋ | 400 |
์ฃผ๋ฌธ(orders) ํ
์ด๋ธ
id | product_id | quantity | order_date |
---|
101 | 1 | 2 | 2023-03-01 |
102 | 2 | 1 | 2023-03-02 |
103 | 3 | 5 | 2023-03-04 |
ํ
์ด๋ธ ์์ฑ, ๋ฐ์ดํฐ ์ฝ์
์ฟผ๋ฆฌ
์ํ(products)
create table products
(
id int unsigned,
name varchar(10),
price int unsigned
);
insert into products (id, name, price)values
(1, "๋ฉํฑ", 1200),
(2, "ํธ๋ํฐ", 800),
(3, "ํ๋ธ๋ ", 400);
์ฃผ๋ฌธ(orders)
create table orders
(
id int unsigned,
product_id int unsigned,
quantity int unsigned,
order_date date
);
insert into orders (id, product_id, quantity, order_date)values
(101, 1, 2, "2023-03-01"),
(102, 2, 1, "2023-03-02"),
(103, 3, 5, "2023-03-04");
์ฐ์ต๋ฌธ์
- ๋ชจ๋ ์ฃผ๋ฌธ์ ์ฃผ๋ฌธ ID์ ์ฃผ๋ฌธ๋ ์ํ์ ์ด๋ฆ์ ๋์ดํ๋ ์ฟผ๋ฆฌ๋ฅผ ์์ฑํด์ฃผ์ธ์!
select o.id, p.name
from orders o left join products p
on o.product_id = p.id;
- ์ด ๋งค์ถ(price * quantity์ ํฉ)์ด ๊ฐ์ฅ ๋์ ์ํ์ ID์ ํด๋น ์ํ์ ์ด ๋งค์ถ์ ๊ฐ์ ธ์ค๋ ์ฟผ๋ฆฌ๋ฅผ ์์ฑํด์ฃผ์ธ์!
select o.product_id, sum(p.price * o.quantity) as total_sales
from orders o left join products p
on o.product_id = p.id
group by o.product_id
order by total_sales desc limit 1;
- ๊ฐ ์ํ ID๋ณ๋ก ํ๋งค๋ ์ด ์๋(quantity)์ ๊ณ์ฐํ๋ ์ฟผ๋ฆฌ๋ฅผ ์์ฑํด์ฃผ์ธ์!
select o.product_id, sum(o.quantity) as total_quantity
from orders o left join products p
on o.product_id = p.id
group by o.product_id;
- 2023๋
3์ 3์ผ ์ดํ์ ์ฃผ๋ฌธ๋ ๋ชจ๋ ์ํ์ ์ด๋ฆ์ ๋์ดํ๋ ์ฟผ๋ฆฌ๋ฅผ ์์ฑํด์ฃผ์ธ์!
select p.name
from orders o left join products p
on o.product_id = p.id
where order_date > "2023-03-03";
- ๊ฐ์ฅ ๋ง์ด ํ๋งค๋ ์ํ์ ์ด๋ฆ์ ์ฐพ๋ ์ฟผ๋ฆฌ๋ฅผ ์์ฑํด์ฃผ์ธ์!
select p.name
from orders o
left join products p on o.product_id = p.id
group by p.id, p.name
order by sum(o.quantity) desc
limit 1;
- ๊ฐ ์ํ ID๋ณ๋ก ํ๊ท ์ฃผ๋ฌธ ์๋์ ๊ณ์ฐํ๋ ์ฟผ๋ฆฌ๋ฅผ ์์ฑํด์ฃผ์ธ์!
select p.id, avg(o.quantity) as avg_quantity
from orders o
left join products p on o.product_id = p.id
group by p.id;
- ํ๋งค๋์ง ์์ ์ํ์ ID์ ์ด๋ฆ์ ์ฐพ๋ ์ฟผ๋ฆฌ๋ฅผ ์์ฑํด์ฃผ์ธ์!
select p.id, p.name
from products p
left join orders o on p.id = o.product_id
where o.id is NULL;