Simplify queries, WITH keyword
Coddy SQL 여정의 기초 섹션에 포함된 레슨 — 72개 중 49번째.
쿼리에 많은 내부 쿼리를 추가하면 너무 복잡해질 수 있습니다. 예를 들어, 여러 하위 쿼리를 가진 쿼리는 다음과 같습니다:
SELECT * FROM table1
WHERE col2 IN (
SELECT col1 FROM table2
WHERE col3 + col2 > 3 AND col5 LIKE '%test%' AND col6 IN (
SELECT col5 FROM table3
WHERE col1 AND col3 OR col2
)
)더 쉽게 하기 위해 WITH query_name AS (...) 키워드를 사용할 수 있습니다. 이 키워드는 쿼리를 이름으로 저장하고 원하는 곳 어디서든 사용할 수 있게 해줍니다:
WITH query1 AS (
SELECT col5 FROM table3
WHERE col1 AND col3 OR col2
), query2 AS (
SELECT col1 FROM table2
WHERE col3 + col2 > 3 AND col5 LIKE '%test%' AND col6 IN query1
)
SELECT * FROM table1
WHERE col2 IN query2 AND col4 IN query1여기서 query1을 query2와 메인 쿼리에서 재사용했습니다.
챌린지
쉬움사용 가능한 테이블 및 열:
<strong>devices_specs</strong>:<strong>device_id</strong>,<strong>width</strong>,<strong>height</strong>,<strong>num_features</strong>,<strong>opinion</strong><strong>devices_score</strong>:<strong>device_id</strong>,<strong>score</strong>
다음과 같은 쿼리를 작성하세요:
- "대형 기기"를 먼저 식별합니다 (<code>width</code>가 200보다 큰 기기)
- 그 다음 이 대형 기기들의 평균 점수를 계산합니다. 이 컬럼을 <code>average_score</code>로 지정하세요.
이 문제를 해결하기 위해 <code>WITH</code> 절을 사용하세요.
치트 시트
WITH query_name AS (...)를 사용해 재사용 가능한 명명된 서브쿼리를 생성하세요:
WITH query1 AS (
SELECT col5 FROM table3
WHERE col1 AND col3 OR col2
), query2 AS (
SELECT col1 FROM table2
WHERE col3 + col2 > 3 AND col5 LIKE '%test%' AND col6 IN query1
)
SELECT * FROM table1
WHERE col2 IN query2 AND col4 IN query1이 접근 방식은 여러 서브쿼리가 포함된 복잡한 쿼리를 더 읽기 쉽게 만들고, 동일한 서브쿼리를 여러 번 재사용할 수 있게 합니다.
직접 해보기
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
기초의 모든 레슨
4More Keywords
The IN keywordThe BETWEEN keywordThe LIKE keywordThe AS keywordRecap - Cellphone Models2Conditions
Conditions BasicsThe AND keywordThe OR keywordThe NOT keywordMultiple Conditions CombinedParenthesisBooleans5Arithmetic Operations
Mathematical OperatorsMathematical ColumnsThe Modulo OperationThe ROUND() Function3Specific Return Format
Null valuesSort Results Part 1Sort Results Part 2Recap - Cyber Security FirmLimit number of recordsRecap - Vehicle Factory6Intro Challenges
Recap - Parliamentary ElectionRecap - Police Criminal ArrestRecap - Bar Beverage ContainerRecap - Engineer new columns9Multiple tables
Basic Join Part 1Basic Join Part 2Recap - JoinSelf joinRecap - Self JoinUnionSimplify queries, WITH keywordRecap - With QueriesRecap - Real Estate Contractor