5. 數據分析及可視化基礎
章節內容
-
資料庫簡介
-
SQL 簡介
-
SQL 語法和基本命令
-
SQL 中的數據類型
-
從單個表中檢索數據
-
對數據進行排序和篩選
-
使用聚合函數
-
在 SQL 中聯接表
-
SQL 中的子查詢
-
創建和修改表
-
索引和優化
數據庫
數據庫(資料庫)Database 是結構化資訊或數據的有組織集合,通常以電子方式存儲在計算機系統中。資料庫通常由資料庫管理系統(DBMS)控制。
常見 Web 應用程式的體系結構
資料庫基本概念
例如,資料庫中有一個名為 phonerec 的表,其中包含以下數據。
〔Tesseract 另讀到 456 字,經詞彙驗證判定為圖內文字/程式碼雜訊,未收錄;需要時見 OCR_uncertain.md〕
C.R.U.D.
在計算機程式設計中,創建、讀取、更新和刪除(CRUD)是持久存儲的四個基本操作。CRUD 有時還用於描述使用者介面約定,這些約定有助於使用基於計算機的表單和報告查看、搜索和更改資訊。
RESTful API
RESTful API 是應用程式介面(API)的一種架構樣式,它使用 HTTP 請求來訪問和使用數據。
CRUD 和 RESTful 是類似的方法。RESTful 服務使用特定的 HTTP 方法,如 GET、POST、PUT 和 DELETE,並要求數據採用 JSON 或 XML 等格式。CRUD 更簡單,非常適合小型專案;REST 為更大、更複雜的系統提供了更大的靈活性和可擴充性。
CREATE READ UPDATE DELETE
Source: Elvurke
SQL 簡介
SQL 是結構化查詢語言的縮寫。
-
它是一種與資料庫交互的語言
-
舉個例子,作為人與人之間的交流,我們可能會問這個問題:「彼得的電話號碼是什麼?
作為資料庫的程式師,我們可以編寫以下代碼:
SELECT phone FROM phoneerc WHERE person = 'Peter';
資料庫管理系統(DBMS)
-
資料庫管理系統(DBMS)是用於創建和管理資料庫的系統軟體。使用者介面(UI)允許對資料進行 CRUD
-
關聯資料庫管理系統(RDBMS)是專門用於關係資料庫或由表組成的資料庫的軟體
-
普及化的 DBMS
MySQL、Oracle、SQL Server、PostgreSQL、MariaDB、SQLite
NoSQL
-
不僅 SQL(Not Only SQL)
-
有時數據無法以這種結構化的方式進行組織。您可能需要一種更有效的方式來存儲和訪問大量數據。
• 資料庫通常被稱為非關係資料庫,它們有各種形狀和大小。
- 眾所周知的 NoSQL
一. MongoDB - 將資料物件存儲在集合和文檔中,而不是表和行中
二. Redis - 儲存 hash、點陣圖、地理空間索引、位字段等數據類型
三. RavenDB - 面向文件的資料庫,將資料儲存為 JSON 文件
在我們的研究範圍內,我們涵蓋了 SQL 基礎知識以及五個流行的資料庫管理系統的細微差別:Microsoft SQL Server,MySQL,Oracle 資料庫,PostgreSQL 和 SQLite。
架構 Schema
關於 SQL 資料庫,需要注意的主要事項是它們需要預定義的架構。您可以將架構視為資料庫中資料的組織或結構化方式。
對於某些關係資料庫管理系統(RDBM),架構的定義各不相同。您可能會看到如下所示的一些設定:
ID int NOT NULL, person varchar (255) NOT NULL, phone int,
SQL 語句
- 這是可以編寫以執行任何 CRUD 操作的通用 SQL 代碼。擁有執行此類任務(編寫語句)的權利的人是資料庫管理員。
SQL 查詢
- 需要訪問資料(從表中讀取)的使用者,執行查詢以查找和顯示。數據分析師和數據科學家就是這些使用者之一。他們可能擁有資料庫的唯讀許可權。
SQL 語句包括更廣泛的操作集,例如 INSERT、UPDATE、DELETE、CREATE、ALTER 和 DROP。
查詢是專門檢索數據並說明闡明其在 SQL 語言中的獨特角色的語句。
查詢
最基本的 SQL 查詢是:
SELECT * FROM my_table;
- 意思是向我顯示名為 my_table 的表中的所有數據(包括所有列和行)。
• 大寫和小寫格式不是強制執行的,但為了可讀性,這是一個很好的樣式約定。
- 查詢中的大寫單詞稱為關鍵字,這意味著 SQL 已保留它們以對數據執行某種操作。
所有其他單詞均為小寫。這包括表名、列名等。
• 為了在表上查找特定數據,我們可以查詢如下內容:
SELECT *
FROM my_table
WHERE column1 > 100
ORDER BY column2 ;
SQL 查詢包含以下子句的組合:
SELECT -- columns to display FROM -- table(s) to pull from WHERE -- filter rows GROUP BY -- split rows into groups HAVING -- filter grouped rows ORDER BY -- columns to sort
執行順序
SQL 代碼按一定的順序執行。如果訪問的數據量很大,查詢方式會影響返回結果的速度。
執行查詢后,這是電腦處理資料的順序:
-
SELECT - 指定要使用 SELECT 顯示的欄位
-
FROM - 使用 FROM 收集所有資料
-
WHERE - 使用 WHERE 篩選資料列
-
GROUP BY - 將行與 GROUP BY 一起分組
-
HAVING - 使用 HAVING 篩選群組行
-
ORDER BY - 使用 ORDER BY 重新排列結果
數據模型
數據模型是一種可視化效果,它匯總了資料庫中所有表之間的關聯方式,以及有關每個表的一些詳細資訊
重要的 DBMS 術語
| Term | Definition | Example |
| Database | A database is a place to store data in an organized way. | This data model shows all of the data in the student grades database. |
| Table | A table is made up of rows and columns. In the data model, they are represented by rectangles. | There are two tables in the student grades database: Students and Grades. |
重要的 DBMS 術語
| Term | Definition | Example |
| Column | A table consists of multiple columns, which are sometimes referred to as attributes or fields. Each column contains a particular type of data. In the data model, all of the columns in a table are listed within each rectangle. | In the Students table, the columns are student_id, student_name, and date_of_birth. |
| Primary Key | A primary key uniquely identifies each row of data in a table. A primary key can be made up of one or more columns in a table. In a data model, it is flagged as pk or with a key icon. | In the Students table, the primary key is the student_id column, meaning that the student_id value is different for each row of data. |
| Term | Definition | Example |
| Foreign Key | A foreign key in a table refers to a primary key in another table. The two tables can be linked together by the common column. A table can have multiple foreign keys. In a data model, it is flagged as fk. | In the Grades table, student_id is a foreign key, meaning that the values in that column match up with values in the corresponding primary key column in the Students table. |
| Relationship | A relationship describes how the rows in one table map to the rows in another table. In a data model, it is represented by a line with symbols at the end points. Common types are one-to-one and one-to-many relationships. | In this data model, the two tables have a one-to-many relationship represented by the fork. One student can have many grades, or one row of the Students table maps to multiple rows in the Grades table. |
放置 SQL 代碼的位置
編寫 SQL 代碼的三種方法:
- RDBMS 軟體
下載 RDBMS 並在終端上運行 MySQL,PostgreSQL,SQL Server 或 SQLite。
- 資料庫工具
下載 DBMS 工具的圖形用戶介面(GUI)版本。拖放友好的視覺化效果。
- 通過其他程式設計語言
編寫 C、Python、PHP、Java 或其他程式設計代碼來執行 SQL。
SQLite
訪問 SQLite 網站並下載官方軟體
-
https://www.sqlite.org/download.html
-
解壓縮檔並在終端上運行 sqlite3 -> sqlite3
創建您的第一個資料庫
在首頁提示~
-> sqlite3 my_new_db.db
sqlite> CREATE TABLE 測試 (id int, num int);
sqlite> 插入到測試值(1,100),(2,200);
sqlite> 從測試限制 1 中選擇 *;
sqlite3 my_new_db.db SQLite version 3.37.0 2021-12-09 01:34:53 Enter ".help" for usage hints. sqlite> CREATE TABLE test (id int, num int); sqlite> INSERT INTO test VALUES (1, 100), (2, 200); sqlite> SELECT * FROM test LIMIT 1; 1|100 sqlite> .databases main: /Users/honcylee/sqlite/my_new_db.db r/w sqlite> .tables test sqlite>
現在,您已經在 my_new_db.db 中創建了一個名為 test 的表
要顯示資料庫、顯示表並退出,請嘗試以下操作:
sqlite> .databases
sqlite> .tables
sqlite> .quit
如果你寫 query,不要錯過查詢命令行末尾的分號!
RDBMS 圖形使用者介面 - SQLiteStudio
您也可以嘗試使用 RDBMS 的 GUI 版本。
現在我們安裝 SQLiteStudio,SQLite 的 GUI 版本工具
https://sqlitestudio.pl/
添加資料庫>
在 SQLITE 資料夾中選擇 my_new_db.db>
還行
您已連接到您建立的資料庫。
打開 SQL 編輯器>查詢
選擇 * FROM 測試;
在結果選項卡中,您會看到以下螢幕。
Keyword 關鍵字是在 SQL 中已經具有一定含義的文字(因此您不能將它們用作表名或字段名)。代碼塊中的所有關鍵字在此處都加粗:
SELECT e.name, COUNT(s.sale_id) AS num_sales
FROM employee e
LEFT JOIN sales s ON e.emp_id = s.emp_id
WHERE YEAR(s.sale_date) = 2021
AND s.closed IS NOT NULL
GROUP BY e.name;
Function 函數是一種特殊類型的關鍵字。它接受零個或多個輸入,對輸入執行某些操作,並返回輸出。在 SQL 中,函數通常後跟括弧,但並非總是如此。
SELECT e.name, COUNT(s.sale_id) AS num_sales
FROM employee e
LEFT JOIN sales s ON e.emp_id = s.emp_id
WHERE YEAR(s.sale_date) = 2021
AND s.closed IS NOT NULL
GROUP BY e.name;
Identifier 標識碼是資料庫物件(如表或列)的名稱。代碼塊中的所有識別碼在此處都以粗體顯示:
SELECT e.name, COUNT(s.sale_id) AS num_sales
FROM employee e
LEFT JOIN sales s ON e.emp_id = s.emp_id
WHERE YEAR(s.sale_date) = 2021
AND s.closed IS NOT NULL
GROUP BY e.name;
Alias 別名僅在查詢期間臨時重新命名列或表。
SELECT e.name, COUNT(s.sale_id) AS num_sales FROM employee e
LEFT JOIN sales s ON e.emp_id = s.emp_id WHERE YEAR(s.sale_date) = 2021
AND s.closed IS NOT NULL
GROUP BY e.name;
語句以關鍵字開頭,以分號結尾。
子句是引用語句的特定部分的一種方式。
expression 運算式可以看作是產生值的公式。
COUNT(s.sale_id)
predicate 調詞是一種邏輯比較,可產生以下三個值之一:
真/假/未知。TRUE/FALSE/UNKNOWN
Comment 註釋 是在執行代碼時被忽略的文字,如下所示。
-- 2021 年完成銷售
要註解掉:
- 單行文字:
-- 這些是我的評論
- 多行文字:
/* 這些是
我的評論 */
SQL Clauses 子句
最簡單的 SELECT 子句列出 FROM 子句中表中的一個或多個列名:
SELECT id, name
FROM owner;
id name
1 Pictured Rocks
2 Michigan Nature
3 AF LLC
4 MI DNR
5 Horseshoe Falls
您還可以在 SELECT 子句中列出更複雜的表達式,以在結果中作為列返回。
SELECT name, ROUND(population * 0.9, 0) FROM county; name ROUND(population * 0.9, 0) Alger 8876 Baraga 7871 Ontonagon 7036 ...
FROM 子句用於指定要檢索的數據來源。
您通常希望從多個表中提取資料,而不是從一個表中檢索數據。
SELECT *
FROM waterfall w JOIN tour t
ON w.id = t.stop;
id name ... name stop ...
1 Munising Falls M-28 1
1 Munising Falls Munising 1
2 Tannery Falls Munising 2
3 Alger Falls M-28 3
3 Alger Falls Munisting 3
...
子查詢是嵌套在另一個查詢中的查詢。FROM 子句中的子查詢應該是獨立的 SELECT 語句,這意味著它們根本不引用外部查詢,可以自行運行。
SELECT w.name AS waterfall_name, o.name AS owner_name FROM (SELECT * FROM owner WHERE type = 'public') o JOIN waterfall w ON o.id = w.owner_id;
waterfall_name owner_name ...... Little Miners Pictured Rocks Miners Falls Pictured Rocks Munising Falls Pictured Rocks Wagner Falls MI DNR
在流覽包含數百萬行的表時,您永遠不想執行 SELECT * FROM my_table。相反,篩選數據是個好主意。
SELECT *
FROM my_table
LIMIT 10;
SELECT *
FROM my_table
WHERE year_id = 2021;
SELECT id, name
FROM waterfall
WHERE name NOT LIKE '%Falls%';
id name
Little Miners
Rapid River FIs
GROUP BY 子句的目的是将行收集到组中,並以某種方式匯總組中的行,最終每個組只返回一行。
SELECT t.name AS tour_name,
COUNT(*) AS num_waterfalls
FROM waterfall w INNER JOIN tour t
ON w.id = t.stop
GROUP BY t.name;
tour_name num_waterfalls
M-28 6
Munising 6
US-2 4
HAVING 子句 對從 GROUP BY 查詢返回的行施加限制。換言之,它允許您在應用 GROUP BY 後對結果進行篩選。
SELECT t.name AS tour_name,
COUNT(*) AS num_waterfalls
FROM waterfall w INNER JOIN tour t
ON w.id = t.stop
GROUP BY t.name
HAVING COUNT(*) = 6;
tour_name num_waterfalls
M-28 6
Munising 6
WHERE Versus HAVING
The purpose of both clauses is to filter data. If you are trying to:
-
Filter on particular columns, write your conditions within the WHERE clause
-
Filter on aggregations, write your conditions within the HAVING clause
The contents of a WHERE and HAVING clause cannot be swapped:
-
Never put a condition with an aggregation in the WHERE clause. You will get an error.
-
Never put a condition in the HAVING clause that does not involve an aggregation. Those conditions are evaluated much more efficiently in the WHERE clause.
ORDER BY 子句用於指定查詢結果的排序方式。
| 無需 排序 | 帶 排序 |
| SELECT COALESCE(o.name, 'Unknown') AS owner, w.name AS waterfall_nameFROM waterfall wLEFT JOIN owner o ON w.owner_id = o.id;ownerwaterfall_namePictured RocksMunising FallsMichigan NatureTannery FallsAF LLCAlger FallsMID DNRWagner FallsUnknownHorseshoe FallsUnknown | SELECT COALESCE(o.name, 'Unknown') AS owner, w.name AS waterfall_nameFROM waterfall wLEFT JOIN owner o ON w.owner_id = o.idORDER BY owner, waterfall_name...owner waterfall_name...AF LLCAlger FallsMID DNRWagner FallsMichigan NatureTannery FallsMichigan NatureTannery FallsMichigan NatureTwin Falls #1Michigan NatureTwin Falls #2... |
可以使用關鍵字 ASCENDING 和 DESCENDING(可以縮寫為 ASC 和 DESC)來控制每列的排序。
SELECT COALESCE(o.name, 'Unknown') AS owner,
w.name AS waterfall_name
...
ORDER BY owner DESC, waterfall_name ASC;
owner waterfall_name
Unknown Agate Falls
Unknown Bond Falls
Unknown Canyon Falls
在創建表之前 !
SQL - 語句
| • 創建新資料庫 | RDBMS Code\nMySQL, CREATE DATABASE my_new_db;\nOracle,\nPostgreSQL,\nSQL Server\nSQLite > sqlite3 my_new_db.db |
| • 創建新表 | CREATE TABLE IF NOT EXISTS my_simple_table (id INTEGER,\ncountry VARCHAR(2),\nname VARCHAR(15)\n); |
創建具有約束的表
將指定哪些資料可以插入到表中的規則。
CREATE TABLE my_table (
id INTEGER NOT NULL,
country VARCHAR(2) DEFAULT 'CA'
CONSTRAINT chk_country
CHECK (country IN ('CA', 'US'),
name VARCHAR(15),
cap_name VARCHAR(15),
CONSTRAINT pk
PRIMARY KEY (id),
CONSTRAINT fk1
CREATE TABLE my_table (
id INTEGER,
country VARCHAR(2),
name VARCHAR(15),
CONSTRAINT unq_country_name
UNIQUE (country, name)
);
插入新的資料列。
RDBMS Code
MySQL, INSERT INTO my_simple_table
PostgreSQL, (id, country, name)
SQL Server, VALUES (2, 'US', 'Selena'),
SQLite (3, 'CA', 'Shawn'),
(4, 'US', 'Sutton');
Oracle INSERT ALL
INTO my_simple_table (id, country, name)
VALUES (2, 'US', 'Selena')
INTO my_simple_table (id, country, name)
VALUES (3, 'CA', 'Shawn')
INTO my_simple_table (id, country, name)
VALUES (4, 'US', 'Sutton')
SELECT * FROM dual;
⚠️ 本頁有 1 段未能本地執行(#2: SyntaxError: invalid syntax (
, line 1)),原因見 OCR_run_report.md
更新一行數據中的值。
UPDATE my_table
SET awards = awards + 1
WHERE country = 'CA';
UPDATE my_table
SET awards = (SELECT MIN(awards) FROM my_table)
WHERE country = 'CA';
删除資料庫很簡單。注意:沒有撤銷!
RDBMS Code
MySQL, DROP DATABASE my_new_db;
Oracle,
PostgreSQL,
SQL Server
SQLite Delete the .db file in the file browser
安装適用於 Python 的驅動程式
| RDBMS | Option | Code |
| SQLite | n/a | No install necessary (Python 3 comes with sqlite3) |
| MySQL | pip | pip install mysql-connector-python |
| conda | conda install -c conda-forge mysql-connector-python | |
| Oracle | pip | pip install cx_Oracle |
| conda | conda install -c conda-forge cx_oracle | |
| PostgreSQL | pip | pip install psycopg2 |
| conda | conda install -c conda-forge psycopg2 | |
| SQL Server | pip | pip install pyodbc |
| conda | conda install -c conda-forge pyodbc |
用於設置資料庫連接的 Python 代碼
範例代碼:
SQLite import sqlite3
conn = sqlite3.connect('my_new_db.db')
MySQL import mysql.connector
conn = mysql.connector.connect(
host='localhost',
database='my_new_db',
user='alice',
password='password')
Oracle # Connecting to Oracle Express Edition
import cx_Oracle
conn = cx_Oracle.connect(dsn='localhost/XE',
user='alice',
password='password')
PostgreSQL import psycopg2
conn = psycopg2.connect(host='localhost',
database='my_new_db',
user='alice',
password='password')
SQL Server # Connecting to SQL Server Express
import pyodbc
conn = pyodbc.connect(driver='{SQL Server}',
host='localhost\SQLEXPRESS',
database='my_new_db',
user='alice',
password='password')
⚠️ 本頁有 1 段未能本地執行(#1: SyntaxError: invalid syntax (
, line 1)),原因見 OCR_run_report.md
一些建議
確定用於編寫查詢的相應 SQL 編輯器
· 避免在 select SQL 查询中使用星號(SELECT *)
將必要的註釋添加到 SQL 查詢中
可讀的 SQL 查詢樣式
從根跟蹤邏輯或嘗試逆向工程
参考及引用
SQLite 命令行 Shell :
SQLite GUI 工具:
SQLite 命令行 Shell 文件:
SQL 語法文檔:
PostgreSQL 命令行 Shell :
PostgreSQL GUI pgAdmin :
MySQL :
教材書目:SQL Pocket Guide, 4^{th} E, Alice Zhao, O'Reilly, 2021
迷你專案
IMDB( )是著名的電影和電視節目資料庫。您是一家電影公司的資料分析師。你的老闆要求你從IMDB研究來年的策略。你的秘書已經準備好了一個名為movies.db的sqlite3資料庫。
請注意,movies 表有一個 id 列,用於唯一標識每部電影,以及電影標題和電影發行年份的列。people 表還具有 id 列,並且還具有每個人的姓名和出生年份的列。
同時,電影評級存儲在評級表中。表中的第一列是 movie_id:引用 movies 表的 id 的外鍵。該行的其餘部分包含有關每部電影的評分以及該電影在 IMDb 上獲得的票數的數據。
最後,明星和導演表將人們與他們表演或導演的電影相匹配。(僅包括主要明星和導演。每個表只有兩列:movie_id 和 person_id,分別引用特定的電影和人物。
擺在您面前的挑戰是編寫 SQL 查詢,通過從一個或多個表中選擇數據來回答各種不同的問題。
對於以下每個問題,您都應編寫一個 SQL 查詢,以輸出每個問題指定的結果。回應必須採用單個 SQL 查詢的形式,但可以在查詢中嵌套其他查詢。
您不應該對任何特定電影或人物的 ID 做出任何假設:即使任何特定電影或人物的 ID 不同,您的查詢也應該是準確的。最後,每個查詢都應僅返回回答問題所需的數據:例如,如果問題僅要求您輸出電影名稱,則查詢不應同時輸出每部電影的發行年份。
數據準備
• 下载 movies.db
在 SQLiteStudio 上連接資料庫
在「查詢」選項卡中,嘗試鍵入一些查詢並運行。瞭解5個表的結構。
在 SQLite 命令行 shell 中,鍵入 .schema
您可以選擇使用任一
命令行 shell 或 GUI 軟體
〔Tesseract 另讀到 539 字,經詞彙驗證判定為圖內文字/程式碼雜訊,未收錄;需要時見 OCR_uncertain.md〕
在接下來的會議中。
進行首次分析
- In 1.sql, write a SQL query to list the titles of all movies released in 2008.
- Your query should output a table with a single column for the title of each movie.
SELECT title FROM movies WHERE year=2008;
(9,480行記錄)
- In 2.sql, write a SQL query to determine the birth year of Emma Stone.
- Your query should output a table with a single column and a single row (plus optional header) containing Emma Stone's birth year.
You may assume that there is only one person in the database with the name Emma Stone.
SELECT birth AS "Emma Stone's birth year" FROM people WHERE name = "Emma Stone";
📁 Image_20261118_0004.pdf(p.151–200)
- In 3.sql, write a SQL query to list the titles of all movies with a release date on or after 2018, in alphabetical order.
-
Your query should output a table with a single column for the title of each movie.
-
Movies released in 2018 should be included, as should movies with release dates in the future.
SELECT title FROM movies WHERE year >= 2018 ORDER BY title ASC;
(35,755行記錄)
- In 4.sql, write a SQL query to determine the number of movies with an IMDb rating of 10.0.
- Your query should output a table with a single column and a single row (plus optional header) containing the number of movies with a 10.0 rating.
SELECT COUNT(movie_id) AS "number of movies with a 10.0 rating"
FROM ratings WHERE rating = 10.0;
- In 5.sql, write a SQL query to list the titles and release years of all Harry Potter movies, in chronological order.
- Your query should output a table with two columns, one for the title of each movie and one for the release year of each movie.
You may assume that the title of all Harry Potter movies will begin with the words "Harry Potter", and that if a movie title begins with the words "Harry Potter", it is a Harry Potter movie.
SELECT title, year FROM movies WHERE title LIKE "Harry Potter%" ORDER BY year ASC;
- In 6.sql, write a SQL query to determine the average rating of all movies released in 2012.
- Your query should output a table with a single column and a single row (plus optional header) containing the average rating.
- In 7.sql, write a SQL query to list all movies released in 2010 and their ratings, in descending order by rating. For movies with the same rating, order them alphabetically by title.
- Your query should output a table with two columns, one for the title of each movie and one for the rating of each movie.
• Movies that do not have ratings should not be included in the result.
SELECT title, rating FROM movies
JOIN ratings ON movies.id=ratings.movie_id
WHERE ratings.rating NOT NULL
AND movies.year = 2010
ORDER BY rating DESC, title ASC;
(6,835行記錄)
- In 8.sql, write a SQL query to list the names of all people who starred in Toy Story.
- Your query should output a table with a single column for the name of each person.
You may assume that there is only one movie in the database with the title Toy Story.
SELECT name FROM people
WHERE id IN (SELECT person_id FROM stars WHERE movie_id IN (SELECT id FROM movies WHERE title = "Toy Story"));
(4行記錄)
- In 9.sql, write a SQL query to list the names of all people who starred in a movie released in 2004, ordered by birth year.
- Your query should output a table with a single column for the name of each person.
People with the same birth year may be listed in any order.
No need to worry about people who have no birth year listed, so long as those who do have a birth year are listed in order.
If a person appeared in more than one movie in 2004, they should only appear in your results once.
SELECT name FROM people WHERE id IN
(SELECT person_id FROM stars JOIN movies
ON movies.id = stars.movie_id
WHERE movies.year = 2004) ORDER BY birth;
(18,013 行記錄)
- In 10.sql, write a SQL query to list the names of all people who have directed a movie that received a rating of at least 9.0.
- Your query should output a table with a single column for the name of each person.
SELECT name FROM people WHERE id IN
(SELECT person_id FROM directors JOIN ratings
WHERE ratings.movie_id = directors.movie_id
AND rating >= 9.0);
(1,841 行記錄)
- In 11.sql, write a SQL query to list the titles of the five highest rated movies (in order) that Chadwick Boseman starred in, starting with the highest rated.
-
Your query should output a table with a single column for the title of each movie.
-
You may assume that there is only one person in the database with the name Chadwick Boseman.
SELECT title FROM movies
JOIN ratings ON movies.id = ratings.movie_id
WHERE id IN
(SELECT movie_id FROM stars
WHERE person_id IN
(SELECT id FROM people
WHERE name = "Chadwick
Boseman"))
ORDER BY ratings.rating DESC
LIMIT 5;
- In 12.sql, write a SQL query to list the titles of all movies in which both Johnny Depp and Helena Bonham Carter starred.
-
Your query should output a table with a single column for the title of each movie.
-
You may assume that there is only one person in the database with the name Johnny Depp.
-
You may assume that there is only one person in the database with the name Helena Bonham Carter.
SELECT title FROM movies, stars A, stars B
ON A.movie_id = B.movie_id
AND
movies.id = A.movie_id
WHERE
A.person_id = (SELECT id from people
WHERE name = "Johnny Depp")
AND
B.person_id = (SELECT id from people
WHERE name = "Helena Bonham Carter")
(5 行記錄)
- In 13.sql, write a SQL query to list the names of all people who starred in a movie in which Kevin Bacon also starred.
-
Your query should output a table with a single column for the name of each person.
-
There may be multiple people named Kevin Bacon in the database. Be sure to only select the Kevin Bacon born in 1958.
-
Kevin Bacon himself should not be included in the resulting list.
SELECT name from people WHERE id IN
(SELECT DISTINCT person_id FROM stars
WHERE movie_id IN
(SELECT movie_id FROM stars
WHERE
person_id = (SELECT id FROM people
WHERE name = "Kevin Bacon" and
birth = 1958)))
AND NOT id = (SELECT id FROM people WHERE name = "Kevin Bacon" and birth = 1958)
(176 行記錄)