SQLBolt:https://sqlbolt.com/lesson/introduction
今天的題目,有提到我們在 Day 14 所使用的 ORDER BY
& LIMIT
。
也有我們沒有用過的 DISTINCT
。
我們先直接來解題:
-- 1. List all directors of Pixar movies (alphabetically), without duplicates
SELECT DISTINCT director FROM movies
ORDER BY director;
-- 筆者解法(搭配 GROUP BY ):
SELECT director FROM movies
GROUP BY director;
-- 2. List the last four Pixar movies released (ordered from most recent to least)
SELECT * FROM movies
ORDER BY year DESC
LIMIT 4;
-- 3. List the first five Pixar movies sorted alphabetically
SELECT * FROM movies
ORDER BY title
LIMIT 5;
-- 4. List the next five Pixar movies sorted alphabetically
SELECT * FROM movies
ORDER BY title
LIMIT 5 OFFSET 5;
-- 筆者解法
SELECT * FROM movies
ORDER BY title
LIMIT 5, 5;
來稍微說明一下,DISTINCT
。
SQLBolt 的說明如下:
Since the DISTINCT keyword will blindly remove duplicate rows, we will learn in a future lesson how to discard duplicates based on specific columns using grouping and the GROUP BY clause.
來解釋一下 LIMIT 語句的用法:
SELECT * FROM movies
ORDER BY title
LIMIT M, N;
SELECT * FROM movies
ORDER BY title
LIMIT M OFFSET N;
參考資料: