在sqlbolt上学习SQL

database

在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;

以上是 在sqlbolt上学习SQL 的全部内容, 来源链接: utcz.com/z/536026.html

回到顶部