在sqlbolt上學習SQL
該網站能夠學習sql基礎,并且能在網頁中直接輸入sql陳述句進行查詢,
學習網站原網址https://sqlbolt.com/ (!部分指令該網站不支持,且存在一些bug!)
該文為SQLBolt學習者提供答案參考
SQL Lesson 1: SELECT queries 101
查詢表格中的特定列
mysql
SELECT 列1, 列2,…
FROM 表;
查詢所有列
SELECT *
FROM 表;
Exercise1 — Tasks

|
1.Find the title of each film 從Movies中找到每個電影的名字(Title) 2.Find the director of each film 找到每個電影的Director 3.Find the title and director of each film 找到每個電影的Title和Director 4.Find the title and year of each film 找到每個電影的Title和Year 5.Find all the information about each film 找到每個電影的所有資訊 |
SELECT title
FROM movies;
SELECT director
FROM movies;
SELECT title, director
FROM movies;
SELECT title, year
FROM movies;
SELECT *
FROM movies;
SQL Lesson 2: Queries with constraints (Pt. 1)
帶約束的選擇查詢
SELECT 列1, 列2, … FROM 表
WHERE 條件1
AND/OR 條件2
AND/OR …;
| Operator | Condition | SQL Example |
|---|---|---|
| =, !=, < <=, >, >= | 標準數值運算子 | 列 != 4 |
| BETWEEN … AND … | 數值在兩個值范圍內 (包含) | 列 BETWEEN 1.5 AND 10.5 |
| NOT BETWEEN … AND … | 數值不在兩個值范圍內 (包含) | 列 NOT BETWEEN 1 AND 10 |
| IN (…) | 數值在串列中 | 列 IN (2, 4, 6) |
| NOT IN (…) | 數值沒在串列中 | 列 NOT IN (1, 3, 5) |
Exercise 2 — Tasks

|
1.Find the movie with a row id of 6 找到Id為6的電影 2.Find the movies released in the years between 2000 and 2010 找到movies中2000到2010年的電影 3.Find the movies not released in the years between 2000 and 2010 找到movies中沒在2000到2010年的電影 4.Find the first 5 Pixar movies and their release year 找到最早的5個皮克斯電影和它們的年份 |
SELECT id, title FROM movies
WHERE id = 6;
SELECT title, year FROM movies
WHERE year BETWEEN 2000 AND 2010;
SELECT title, year FROM movies
WHERE year < 2000 OR year > 2010;
SELECT Title, Year FROM movies WHERE id <= 5;
SQL Lesson 3: Queries with constraints (Pt. 2)
| Operator | Condition | Example |
|---|---|---|
| = | 區分大小寫的字串精確比較 (注意單個的相等) | 列 = "abc" |
| != or <> | 區分大小寫的字串不等精確比較 | 列 != "abcd" |
| LIKE | 不區分大小寫的精確字串比較 | 列 LIKE "ABC" |
| NOT LIKE | 不區分大小寫的精確字串不等比較 | 列 NOT LIKE "ABCD" |
| % | 用于字串中的任意位置,以匹配由零個或多個字符組成的序列 (只和 LIKE 或 NOT LIKE 同時使用) | 列 LIKE "%AT%" (matches "AT", "ATTIC", "CAT" or even "BATS") |
| _ | 用于字串中的任意位置匹配單個字符 (只和 LIKE 或 NOT LIKE 同時使用) | 列 LIKE "AN_" (matches "AND", but not "AN") |
| IN (…) | 字串存在于串列中 | 列 IN ("A", "B", "C") |
| NOT IN (…) | 字串不在串列中 | 列 NOT IN ("D", "E", "F") |
帶約束的選擇查詢
SELECT 列1, 列2, …
FROM 表
WHERE 條件1
AND/OR 條件2
AND/OR …;
Exercise 3 — Tasks

|
1.Find all the Toy Story movies 找到所有的Toy Story電影 2.Find all the movies directed by John Lasseter 找到所有由John Lasseter導演的電影 3.Find all the movies (and director) not directed by John Lasseter 找到所有的不是John Lasseter導演的不是電影(和Director) 4.Find all the WALL-* movies 找到所有的WALL-*電影 |
SELECT title, director FROM movies
WHERE title LIKE "Toy Story%";
SELECT title, director FROM movies
WHERE director = "John Lasseter";
SELECT title, director FROM movies
WHERE director != "John Lasseter";
SELECT * FROM movies WHERE Title LIKE "WALL-%";
SQL Lesson 4: Filtering and sorting Query results
唯一結果的選擇查詢
SELECT DISTINCT 列1, 列2, …
FROM 表
WHERE condition(s);
帶有有序結果的選擇查詢
SELECT 列1, 列2, …
FROM 表 WHERE 條件
ORDER BY 列 ASC/DESC;#ASC升序/DESC降序
限制行的選擇查詢
SELECT 列1, 列2, …
FROM 表
WHERE 條件
ORDER BY 列 ASC/DESC
LIMIT 數量 OFFSET 開始位置;
Exercise 4 — Tasks

|
1.List all directors of Pixar movies (alphabetically), without duplicates 列出所有的皮克斯電影的directors(照字母順序排列),沒有重復 2.List the last four Pixar movies released (ordered from most recent to least) 列出最近上映的四部皮克斯電影(從最近源到最早) 3.List the first five Pixar movies sorted alphabetically 按字母順序列出皮克斯的前五部電影 4.List the next five Pixar movies sorted alphabetically 按字母順序列出皮克斯5到10部電影 |
SELECT DISTINCT director FROM movies
ORDER BY director ASC;
SELECT title, year FROM movies
ORDER BY year DESC
LIMIT 4;
SELECT title FROM movies
ORDER BY title ASC
LIMIT 5;
SELECT title FROM movies
ORDER BY title ASC
LIMIT 5 OFFSET 5;
SQL Review: Simple SELECT Queries
選擇查詢
SELECT 列1, 列2, …
FROM 表
WHERE 條件
ORDER BY 列 ASC/DESC
LIMIT 顯示數量 OFFSET 開始位置;
Review 1 — Tasks

|
1.List all the Canadian cities and their populations 列出所有加拿大城市(City)及其人口(Population) 2.Order all the cities in the United States by their latitude from north to south 按照從北到南的緯度把美國所有的城市排序 3.List all the cities west of Chicago, ordered from west to east 列出芝加哥以西的所有城市,按從西到東的順序 4.List the two largest cities in Mexico (by population) 列出墨西哥最大的兩個城市(按人口分) 5.List the third and fourth largest cities (by population) in the United States and their population 列出美國第三和第四大城市(按人口)及其人口 注:Latitude 緯度, Longitude 經度 |
SELECT city, population
FROM north_american_cities
WHERE country = "Canada";
SELECT city, latitude
FROM north_american_cities
WHERE country = "United States"
ORDER BY latitude DESC;
SELECT *
FROM north_american_cities
WHERE Longitude < -87.5
ORDER BY Longitude ASC;
SELECT * FROM north_american_cities
WHERE Country='Mexico'
ORDER BY Population
DESC LIMIT 2;
SELECT * FROM north_american_cities
WHERE Country='United States'
ORDER BY Population
DESC LIMIT 2 OFFSET 2;
SQL Lesson 6: Multi-table queries with JOINs
在多個表上使用INNER JOIN選擇查詢
SELECT 列1, 列2, …
FROM 表1
INNER JOIN 表2
ON 表1.id = 表2.id
WHERE 條件
ORDER BY 列, … ASC/DESC
LIMIT 顯示數量 OFFSET 開始位置;
Exercise 6 — Tasks

|
1.Find the domestic and international sales for each movie 找出每部電影(Title)在國內和國際上的銷售情況(Domestic_sales,International_sales) 2.Show the sales numbers for each movie that did better internationally rather than domestically 展示每一部在國際(International_sales)上比在國內(Domestic_sales)銷量更好的電影 3.List all the movies by their ratings in descending order 把所有的電影按評分(Rating)降序排列 |
SELECT title, domestic_sales, international_sales
FROM movies
INNER JOIN boxoffice
ON movies.id = boxoffice.movie_id;
SELECT *
FROM movies
INNER JOIN boxoffice
ON movies.id = boxoffice.movie_id
WHERE international_sales > domestic_sales;
SELECT title, rating
FROM movies
INNER JOIN boxoffice
ON movies.id = boxoffice.movie_id
ORDER BY rating DESC;
SQL Lesson 7: OUTER JOINs
在多個表上使用左/右/全連接選擇查詢
SELECT 列1, 列2, …
FROM 表1
INNER/LEFT/RIGHT/FULL JOIN 表2
ON 表1.id = 表2.matching_id
WHERE 條件
ORDER BY 列1, … ASC/DESC
LIMIT 數量 OFFSET 開始位置;
Exercise 7 — Tasks

|
1.Find the list of all buildings that have employees 找到所有有員工的建筑串列 2.Find the list of all buildings and their capacity 找到所有建筑及其Capacity的串列 3.List all buildings and the distinct employee roles in each building (including empty buildings) 列出所有建筑和每個建筑中不同的員工職責(role)(包括空的建筑) |
SELECT DISTINCT building_name
FROM buildings
LEFT JOIN employees
ON buildings.building_name = employees.building
WHERE building IS NOT NULL;
SELECT *
FROM buildings;
SELECT DISTINCT building_name, role
FROM buildings
LEFT JOIN employees
ON buildings.building_name = employees.building;
SQL Lesson 8: A short note on NULLs
對NULL值有約束的選擇查詢
SELECT 列1, 列2, …
FROM 表
WHERE 列 IS/IS NOT NULL
AND/OR 條件2
AND/OR …;
Exercise 8 — Tasks

|
1.Find the name and role of all employees who have not been assigned to a building 查找所有尚未分配到大樓的員工的名字和職責 2.Find the names of the buildings that hold no employees 找出沒有員工的大樓的名字 |
SELECT name, role FROM employees
WHERE building IS NULL;
SELECT DISTINCT building_name
FROM buildings
LEFT JOIN employees
ON building_name = building
WHERE name IS NULL;
SQL Lesson 9: Queries with expressions
帶有運算式的查詢示例
SELECT particle_speed / 2.0 AS half_particle_speed
FROM physics_data
WHERE ABS(particle_position) * 10.0 > 500;
帶運算式的別名選擇查詢
SELECT col_expression AS expr_description, …
FROM mytable;
具有列和表別名的查詢示例
SELECT column AS better_column_name, …
FROM a_long_widgets_table_name AS mywidgets
INNER JOIN widget_sales
ON mywidgets.id = widget_sales.widget_id;
Exercise 9 — Tasks

|
1.List all movies and their combined sales in millions of dollars 列出所有電影及其總銷售額(以百萬美元計) 2.List all movies and their ratings in percent 列出所有電影及其收視率(使用百分比) 3.List all movies that were released on even number years 列出所有偶數年發行的電影 |
SELECT title,(domestic_sales + international_sales)/1000000 AS million_dollars
FROM movies
JOIN boxoffice
ON movies.id = boxoffice.movie_id;
SELECT title, rating * 10 AS rating_percent
FROM movies
JOIN boxoffice
ON movies.id = boxoffice.movie_id;
SELECT title, year
FROM movies
WHERE year % 2 = 0;
SQL Lesson 10: Queries with aggregates (Pt. 1)
Select query with aggregate functions over all rows
SELECT AGG_FUNC(column_or_expression) AS aggregate_description, …
FROM mytable
WHERE constraint_expression;
| Function | Description |
|---|---|
| COUNT(), COUNT(column*) | 一個常用函式,用于在未指定列名的情況下統計組中的行數,否則,計算指定列中具有非空值的組中的行數, |
| MIN(column) | 為組中的所有行查找指定列中的最小數值 |
| MAX(column) | 為組中的所有行在指定列中查找最大的數值, |
| AVG(column) | 在指定列中查找組中所有行的平均數值, |
| SUM(column) | 在指定的列中查找組中各行的所有數值之和, |
Exercise 10 — Tasks

|
1.Find the longest time that an employee has been at the studio 找出員工在作業室作業的最長時間 2.For each role, find the average number of years employed by employees in that role 對于每個角色,查找該角色雇員的平均作業年限 3.Find the total number of employee years worked in each building 查找在每個建筑物作業的員工總年數 |
SELECT MAX(years_employed)
FROM employees;
SELECT role, AVG(years_employed)
FROM employees
GROUP BY role;
SELECT building, SUM(years_employed)
FROM employees
GROUP BY building;
SQL Lesson 11: Queries with aggregates (Pt. 2)
選擇具有約束的查詢
SELECT group_by_column, AGG_FUNC(column_expression) AS aggregate_result_alias, …
FROM 表名
WHERE 條件
GROUP BY 列名
HAVING 組條件;
Exercise 11 — Tasks

|
1.Find the number of Artists in the studio (without a HAVING clause) 查找作業室中藝術家的數量(不用 HAVING 子句) 2.Find the number of Employees of each role in the studio 查找作業室中每種職責的雇員人數 3.Find the total number of years employed by all Engineers 找到所有工程師(Engineer)的總受雇年數(Years_employed) |
SELECT role, COUNT(*)
FROM employees
WHERE role = "Artist";
SELECT role, COUNT(*)
FROM employees
GROUP BY role;
SELECT role, SUM(years_employed)
FROM employees
GROUP BY role
HAVING role = "Engineer";
SQL Lesson 12: Order of execution of a Query
完整的SELECT查詢
SELECT DISTINCT column, AGG_FUNC(column_or_expression), …
FROM mytable
JOIN another_table
ON mytable.column = another_table.column
WHERE constraint_expression
GROUP BY column
HAVING constraint_expression
ORDER BY column ASC/DESC
LIMIT count OFFSET COUNT;
Exercise 12 — Tasks

|
1.Find the number of movies each director has directed 找出每位導演導演的電影數量 2.Find the total domestic and international sales that can be attributed to each director 找出每一位導演在國內和國際上的總銷售額 |
SELECT director, COUNT(id) as Num_movies_directed
FROM movies
GROUP BY director;
SELECT director, SUM(domestic_sales + international_sales) as Cumulative_sales_from_all_movies
FROM movies
INNER JOIN boxoffice
ON movies.id = boxoffice.movie_id
GROUP BY director;
SQL Lesson 13: Inserting rows
包含所有列的值的插入陳述句
INSERT INTO 表名
VALUES (value_or_expr, another_value_or_expr, …),
(value_or_expr_2, another_value_or_expr_2, …),
…;
插入特定列的陳述句
INSERT INTO 表名
(列名1, 列名2, …)
VALUES (value_or_expr, another_value_or_expr, …),
(value_or_expr_2, another_value_or_expr_2, …),
…;
Exercise 13 — Tasks

|
1.Add the studio’s new production, Toy Story 4 to the list of movies (you can use any director) 將該作業室的新作品Toy Story 4添加到電影串列中(你可以使用任何導演) 2.Toy Story 4 has been released to critical acclaim! It had a rating of 8.7, and made 340 million domestically and 270 million internationally. Add the record to the BoxOffice table. Toy Story 4上映后廣受好評!它的評分為8.7,國內票房為3.4億美元,國際票房為2.7億美元,將記錄添加到BoxOffice表中, |
INSERT INTO movies
VALUES (4, "Toy Story 4", "El Directore", 2020, 90);
INSERT INTO boxoffice
VALUES (4, 8.7, 340000000, 270000000);
SQL Lesson 14: Updating rows
跟新表資料
UPDATE mytable
SET 列1 = value_or_expr,
列2 = another_value_or_expr,
…
WHERE condition;
Exercise 14 — Tasks

|
1.The director for A Bug's Life is incorrect, it was actually directed by John Lasseter A Bug's Life的導演是錯誤的,實際上是John Lasseter導演的 2.The year that Toy Story 2 was released is incorrect, it was actually released in 1999 Toy Story 2發布的年份是不正確的,它實際上是在1999年上映的 3.Both the title and director for Toy Story 8 is incorrect! The title should be "Toy Story 3" and it was directed by Lee Unkrich Toy Story 2的片名和導演都是錯誤的!標題應該是“Toy Story 3”,它是由李昂克里奇導演的 |
UPDATE movies
SET director = "John Lasseter"
WHERE Title = 'A Bug's Life';
UPDATE Movies
SET Year = 1999
WHERE Title='Toy Story 2';
SQL Lesson 15: Deleting rows
帶條件的洗掉陳述句
DELETE FROM 表
WHERE 條件;
Exercise 15 — Tasks

|
1.This database is getting too big, lets remove all movies that were released before 2005. 這個資料庫太大了,讓我們洗掉所有2005年之前上映的電影, 2.Andrew Stanton has also left the studio, so please remove all movies directed by him. Andrew Stanton也離開了作業室,所以請洗掉他執導的所有電影, |
DELETE FROM movies
WHERE year<2005;
DELETE FROM movies
WHERE director = 'Andrew Stanton';
SQL Lesson 16: Creating tables
創建帶有可選表格約束和默認值的表格陳述句
CREATE TABLE IF NOT EXISTS 表 (
列名1 資料型別 可選表格約束 DEFAULT 預設值,
列名2 資料型別 可選表格約束 DEFAULT 預設值,
…
);
Table data types
| Data type | Description |
|---|---|
INTEGER, BOOLEAN |
整數資料型別可以存盤整數值,如數字的計數或年齡,在某些實作中,布林值只是表示為0或1的整數值, |
FLOAT, DOUBLE, REAL |
浮點資料型別可以存盤更精確的數值資料,如測量值或小數值,根據該值所需的浮點精度,可以使用不同的型別, |
CHARACTER(num_chars), VARCHAR(num_chars), TEXT |
基于文本的資料型別可以在各種地區存盤字串和文本,在處理這些列時,不同型別之間的區別通常相當于底層資料庫的效率,CHARACTER和VARCHAR(可變字符)型別都是用它們可以存盤的最大字符數指定的(較長的值可能會被截斷),因此使用大表存盤和查詢更有效, |
DATE, DATETIME |
SQL還可以存盤日期和時間戳,以跟蹤時間序列和事件資料,使用它們可能很棘手,特別是在跨時區操作資料時, |
BLOB |
最后,SQL可以將二進制資料以blob的形式直接存盤在資料庫中,這些值對資料庫通常是不透明的,因此通常必須使用正確的元資料存盤它們,以便查詢它們, |
| Docs: MySQL, Postgres, SQLite, Microsoft SQL Server |
Table constraints
| Constraint | Description |
|---|---|
PRIMARY KEY |
這意味著這個列中的值是唯一的,每個值都可以用來標識該表中的一行, |
AUTOINCREMENT |
對于整型值,這意味著值將自動填充,并在每次插入行時遞增,不是所有資料庫都支持, |
UNIQUE |
這意味著這一列中的值必須是唯一的,因此不能在這一列中插入與表中另一行值相同的行,與“主鍵”不同的是,它不必是表中某一行的鍵, |
NOT NULL |
這意味著插入的值不能是' NULL ', |
CHECK (expression) |
這允許您運行更復雜的運算式來測驗插入的值是否有效,例如,您可以檢查值是否為正,或大于特定的大小,或以特定的前綴開頭,等等, |
FOREIGN KEY |
這是一種一致性檢查,確保此列中的每個值與另一個表中某列中的另一個值相對應,例如,如果有兩個表,一個按ID列出所有雇員,另一個列出他們的工資資訊,那么“FOREIGN KEY”可以確保工資表中的每一行都對應于主employee串列中的一個有效雇員, |
An example
Movies table schema
CREATE TABLE movies (
id INTEGER PRIMARY KEY,
title TEXT,
director TEXT,
year INTEGER,
length_minutes INTEGER
);
Exercise 16 — Tasks
|
1.創建一個名為Database的新表,包含以下列: -Name描述資料庫名稱的字串(文本) -Version該資料庫的最新版本號(浮點數) -Download_count下載資料庫的整數計數 該表沒有約束, |
CREATE TABLE Database (
Name TEXT,
Version FLOAT,
Download_count INTEGER
);
SQL Lesson 17: 修改表
添加列
修改表以添加新列
ALTER TABLE 表名
ADD 列名 *資料型別* 可選表格約束
DEFAULT 預設值;
移除列
修改表以洗掉列
ALTER TABLE 表名
DROP 列名;
重命名表
更改表名
ALTER TABLE 表名
RENAME TO 新表名;
Exercise 17 — Tasks

|
1.Add a column named **Aspect_ratio** with a **FLOAT** data type to store the aspectratio each movie was released in. 添加一個名為 Aspect _ ratio 的列,該列具有 FLOAT 資料型別,用于存盤年發布的每部電影的 Aspect-ratio, 2.Add another column named **Language** with a **TEXT** data type to store the language that the movie was released in. Ensure that the default for this language is **English**. 添加另一個名為 Language 的帶有 TEXT 資料型別的列,以存盤電影發行的語言,確保此語言的默認值為英語, |
ALTER TABLE Movies
ADD COLUMN Aspect_ratio
FLOAT DEFAULT 2.39;
ALTER TABLE Movies
ADD COLUMN Language TEXT
DEFAULT "English";`
SQL Lesson 18: Dropping tables
Drop table statement
DROP TABLE IF EXISTS mytable;
Exercise 18 — Tasks

|
1. We've sadly reached the end of our lessons, lets clean up by removing the *Movies* table 我們已經很遺憾地結束了我們的課程,讓我們洗掉Movies表 2. And drop the *BoxOffice* table as well 并且同樣的去除BoxOffice表 |
DROP TABLE Movies;
DROP TABLE BoxOffice;
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/337908.html
標籤:MySQL
