[LeetCode] 1045. Customers Who Bought All Products
๐ข ๋ณธ ํฌ์คํ ์ ํ์ฉ๋๋ ๊ธฐ๋ณธ ๋ฌธ์ ๋ฐ ์๋ฃ ์ถ์ฒ๋
๋ฆฌํธ์ฝ๋ Problems, https://leetcode.com/problemset/all/์์ ๋ฐํ๋๋ค.
โ๋ฌธ์
https://leetcode.com/problems/customers-who-bought-all-products/
Customers Who Bought All Products - LeetCode
Can you solve this real interview question? Customers Who Bought All Products - Table: Customer +-------------+---------+ | Column Name | Type | +-------------+---------+ | customer_id | int | | product_key | int | +-------------+---------+ There is no pri
leetcode.com
Table: Customer
Table: Product
Write an SQL query to report the customer ids from the Customer table that bought all the products in the Product table.
Return the result table in any order.
The query result format is in the following example.
โ ํ์ด
๋ฌธ์ ์๊ตฌ์ฌํญ
Product ํ ์ด๋ธ์ ์๋ ๋ชจ๋ product๋ฅผ ๊ตฌ๋งคํ ๊ณ ๊ฐ์ id๋ฅผ ์ถ๋ ฅํด์ผ ํ๋ค.
์ด๋ฒ ๋ฌธ์ ์์๋ MySQL์์ ์ ๊ณตํ๋ ์๋ก์ด ๋ฌธ์์ด ํฉ์น๋ ๋ฌธ๋ฒ GROUP_CONCAT()์ ์ฌ์ฉํ๋ค.
โ ๋ฌธ๋ฒ :
GROUP_CONCAT(์ปฌ๋ผ๋ช ORDER BY ์ปฌ๋ผ๋ช SEPARATOR ๊ตฌ๋ถ์)
· SEPARATOR ๊ธฐ๋ณธ๊ฐ์ ','
· CONCAT ํ ์ปฌ๋ผ ๋ฐ์ดํฐ์ ๋ํด ์ ๋ ฌ ์กฐ๊ฑด์ ๋ถ์ฌํ๊ณ ์ถ์ ๋, ORDER BY ์ปฌ๋ผ๋ช ์ ์ฌ์ฉํ๋ฉด ๋๋ค.
โ Customerํ ์ด๋ธ์์ id๋ณ๋ก ์ฐ product_key๋ฅผ group_concat์ ํ์ฉํด์ ์ฅ๋ฐ๊ตฌ๋์ฒ๋ผ pd_keys ์ปฌ๋ผ์ ๋ด๊ณ
โก id๋ณ๋ก ๋ด์ pd_keys๊ฐ Product ํ ์ด๋ธ์ product_key์ปฌ๋ผ ๊ฐ์ ํฉ์น pd_keys ์ปฌ๋ผ๊ณผ ๋์ผํ ์ง¹ ๋น๊ตํด์ ๋์ผํ ๊ณ ๊ฐ์ ID๋ง ์ถ๋ ฅํ๋ค.
SELECT customer_id
FROM (
SELECT customer_id, GROUP_CONCAT(DISTINCT product_key ORDER BY product_key SEPARATOR ',') AS pd_keys
FROM Customer
GROUP BY 1) T1
WHERE pd_keys = (SELECT GROUP_CONCAT(product_key ORDER BY product_key SEPARATOR ',') AS pd_keys
FROM Product)
;
¹ product_key๊ฐ ๋ชจ๋ ์๋ค๋ ๊ฒ = ๋ชจ๋ ์ํ์ ๊ตฌ๋งคํ๋ค. ๋ ์๋ฏธ
<์ฐธ๊ณ ์๋ฃ>
์ฐธ๊ณ ๋งํฌ์์ Oracle์์ ๋์ผํ ์ญํ ์ ํ๋ listagg ์ ๋ํด์๋ ๊ณต๋ถํ ์ ์๋ค.
[SQL] ๊ทธ๋ฃน๋ณ ๋ฌธ์์ด ๋ฌถ๊ธฐ (group_concat, listag)
MySQL ๊ทธ๋ฃน๋ณ ๋ฌธ์์ด ๋ฌถ๊ธฐ ๊ทธ๋ฃน๋ณ๋ก ์ปฌ๋ผ ๋ฐ์ดํฐ(๋ฌธ์์ด)๋ฅผ ๋ฌถ์ด์ ๋ณด๊ณ ์ถ์ ๋๊ฐ ์์ต๋๋ค. ์ด๋ฐ ์ํฉ์ด ๋ฐ์ํ์ ๋ MySQL์ด๋ Oracle์์ ์ ์ฉํ๊ฒ ์ฌ์ฉํ ์ ์๋ ํจ์๋ฅผ ๋น๊ตํด์ ์๋ ค๋๋ฆฌ๋๋ก
codingspooning.tistory.com
โ ๊ฐ์ธํ๊ณ
๋ฌธ์ ํ์ด์ ์๋ธ์ฟผ๋ฆฌ๋ฅผ ๋๋ฒ์ด๋ ์ฌ์ฉํด์ ์ฟผ๋ฆฌ ์คํ์ ์๊ฐ์ด ๊ฑธ๋ฆด ๋ฏ ํ๋ค.