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 (SELECT col1 FROM query2) AND col4 IN (SELECT col5 FROM 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>
다음과 같은 쿼리를 작성하세요:
- 먼저 "large devices" (
width가 200보다 큰 기기)를 식별합니다. - 그런 다음 이 대형 기기들의 평균 점수를 계산합니다. 이 컬럼의 이름을
average_score로 지정하세요.
이 문제를 해결하기 위해 WITH 절을 사용하세요.
직접 해보기
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
기초의 모든 레슨
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