Simplify queries, WITH keyword
CoddyのSQLジャーニー「基礎」セクションの一部 — レッスン 49/72。
クエリに多くの内部クエリを追加すると、非常に煩雑になることがあります。例えば、多くのサブクエリを持つクエリの例を以下に示します:
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