728x90
더보기
https://dev.mysql.com/doc/refman/8.0/en/with.html
MySQL :: MySQL 8.0 Reference Manual :: 13.2.20 WITH (Common Table Expressions)
13.2.20 WITH (Common Table Expressions) A common table expression (CTE) is a named temporary result set that exists within the scope of a single statement and that can be referred to later within that statement, possibly multiple times. The following disc
dev.mysql.com
13.2.20 WITH (Common Table Expressions)
Common Table Expressions
WITH
cte1 AS (SELECT a, b FROM table1),
cte2 AS (SELECT c, d FROM table2)
SELECT b, d FROM cte1 JOIN cte2
WHERE cte1.a = cte2.c;
WITH 안에 하나 이상의 쿼리 절을 사용함
cte1, cte2 테이블을 정의함
WITH RECURSIVE cte AS
(
SELECT 1 AS n, 'abc' AS str
UNION ALL
SELECT n + 1, CONCAT(str, str) FROM cte WHERE n < 3
)
SELECT * FROM cte;
WITH RECURSIVE cte AS
(
SELECT 1 AS n, 'abc' AS str
UNION ALL
SELECT n + 1, CONCAT(str, str) FROM cte WHERE n < 3
)
SELECT * FROM cte;
nonstrict SQL mode, the statement produces this output
UNION 은 붙인다는 뜻이다
컬럼 n, str 을 붙임
+------+------+
| n | str |
+------+------+
| 1 | abc |
| 2 | abc |
| 3 | abc |
+------+------+
# UNION 결과 : 1,2 출력
SELECT 1 AS num
UNION
SELECT 2 AS num;Copy
# WITH, UNION 결과 : 1,2 출력
WITH test AS
(
SELECT 1 AS num
UNION ALL
SELECT 2 AS num
)
SELECT * FROM test;Copy
# WITH, UNION 결과 : 1,2,2,2,... (emp테이블의 행수만큼 2가 반복됨)
WITH test AS
(
SELECT 1 AS num
UNION ALL
SELECT 2 AS num FROM emp # 이 문장은 emp 테이블의 행수만큼 반복된다
)
SELECT * FROM test;
728x90
'Web > DB' 카테고리의 다른 글
[mysql] Recursive (0) | 2023.05.02 |
---|---|
[mysql] 멀티게시판 구현 설계 (0) | 2023.05.02 |
[mysql] with 절(가상테이블) 01 (0) | 2023.05.01 |
[mariaDB Mac] 설치 팁 (0) | 2023.04.13 |
[mariaDB] Spring + mariaDB 연동 (0) | 2023.04.04 |