CTE
Common Table Expression ์ ์ฝ์๋ก ๊ณตํต ํ ์ด๋ธ ํํ์์ด๋ค.
๋ช ๋ น๋ฌธ ๋ด์์ ์์๋ก ์์ฑํ ํ ์ด๋ธ๋ก ์ฟผ๋ฆฌ ์คํ ์ค์๋ง ์ง์๋๊ณ ํ์ํ์ด๋ธ๊ณผ ๋ฌ๋ฆฌ ์ฟผ๋ฆฌ ์คํ ์ค์ ์ฌ๋ฌ๋ฒ ์ฐธ์กฐ ๋ ์ ์๋ค.
๊ธฐ๋ณธ ๊ตฌ๋ฌธ
WITH cte_name (column_list) AS (
query
)
SELECT * FROM cte_name;
WITH AS ์ ์ ์ด์ฉํ์ฌ ()์์ ์ฟผ๋ฆฌ๋ฌธ[Select from where]์ ์ด์ฉํด ์์ ํ ์ด๋ธ cte_name์ ๋ง๋ค์ด ์ด CTE์ ์ ๊ทผ์ด ๊ฐ๋ฅํ๋ค.
์์ ๊ตฌ๋ฌธ
WITH topsales2003 AS (
SELECT
salesRepEmployeeNumber employeeNumber,
SUM(quantityOrdered * priceEach) sales
FROM
orders
INNER JOIN
orderdetails USING (orderNumber)
INNER JOIN
customers USING (customerNumber)
WHERE
YEAR(shippedDate) = 2003
AND status = 'Shipped'
GROUP BY salesRepEmployeeNumber
ORDER BY sales DESC
LIMIT 5
)
SELECT
employeeNumber,
firstName,
lastName,
sales
FROM
employees
JOIN
topsales2003 USING (employeeNumber);
orders, orderdetails, customers ์ธ๊ฐ์ ํ ์ด๋ธ์ joinํ CTE๋ฅผ employees์ joinํ์ฌ selectํ๋ ์ฟผ๋ฆฌ๋ฌธ
์ฌ๊ท์ CTE (RECURSIVE CTE)
Mysql 8.0์ด์์์๋ง ์ฌ์ฉํ ์ ์๊ณ , anchor member(์ฌ๊ท ๋ฉค๋ฒ,column)๋ฅผ ์ฌ๊ท ์กฐ๊ฑด์์ ๋ฐ๋ผ ๋ฐ๋ณตํ๋ฉฐ UNION ALL
, UNION DISTINCT
์ ๊ฒฐํฉํ์ฌ ์ฌ๊ท ๋งด๋ฒ๋ค์ ํฉ์น TABLE์ ์์ฑํ๋ค.
์์ ๊ตฌ๋ฌธ
WITH RECURSIVE cte_name AS (
initial_query -- anchor member
UNION ALL
recursive_query -- recursive member that references to the CTE name
)
SELECT * FROM cte_name;
์ฌ๊ท ๋ฉค๋ฒ๋ ์ง๊ณํจ์(MAX,MIN,SUM,AVG,COUNT..), GROUP BY, ORDER BY, LIMIT, DISTINCT ๋ฅผ ํฌํจ ํ ์ ์๋ค. (UNION DISTINCT๋ฅผ ์ฌ์ฉํ๋ ๊ฒฝ์ฐ DISTINCT๋ ์ฌ์ฉ๊ฐ๋ฅํ๋ค)
์ฌ์ฉ ์์ ๊ตฌ๋ฌธ
WITH RECURSIVE
cte AS (
SELECT 0 AS HOUR
UNION ALL
SELECT HOUR + 1
FROM cte
WHERE HOUR <23)
SELECT
hour, count(o.datetime)
FROM
cte
left JOIN ANIMAL_OUTS AS O
ON cte.hour = HOUR(O.DATETIME)
group by hour;
์ซ์ 0๋ถํฐ 23๊น์ง 1์ฉ ์ฆ๊ฐํ๋ COLUMN(HOUR)๋ฅผ ๊ฐ์ง TABLE (CTE)๋ฅผ ์์ฑํ์ฌ ์ด cte์ animal_outs๋ผ๋ ํ ์ด๋ธ๊ณผ joinํ ์ฟผ๋ฆฌ๋ฌธ์ด๋ค.
WITH RECURSIVE employee_paths AS
( SELECT employeeNumber,
reportsTo managerNumber,
officeCode,
1 lvl
FROM employees
WHERE reportsTo IS NULL
UNION ALL
SELECT e.employeeNumber,
e.reportsTo,
e.officeCode,
lvl+1
FROM employees e
INNER JOIN employee_paths ep ON ep.employeeNumber = e.reportsTo )
SELECT employeeNumber,
managerNumber,
lvl,
city
FROM employee_paths ep
INNER JOIN offices o USING (officeCode)
ORDER BY lvl, city;
employeesํ ์ด๋ธ์์ reportsTo๊ฐ NULL์ธ row๋ฅผ ์์์ผ๋ก ํด๋น row์ employeeNumber์ ๊ฐ์ ๊ฐ์ reportsTo๋ฅผ ๊ฐ๋ row๋ค์ lvl์ ์ฆ๊ฐ ์ํค๊ณ ์ด row์ ๋ํด ๋ ๋น๊ตํ๋ฉฐ ์ฌ๊ท์ ์ผ๋ก ์ํํ์ฌ employeeNumber์ ๊ฐ์ reportsTo์ ๊ฐ์ ๊ฐ๋ row๊ฐ ์์๋๊น์ง ๋ฐ๋ณตํ์ฌ cte๋ฅผ ์์ฑํ๋ค.
์ด ์์ฑํ cte์ offices ํ ์ด๋ธ์ joinํ์ฌ selectํ๋ ์ฟผ๋ฆฌ๋ฌธ์ด๋ค.
Last updated