A3.3.2 · Database programming
A3.3.2 · 数据库编程
Constructing queries between two tables
构建涉及两张表的查询
A single table can only ever answer questions about itself, the moment a question needs "which artist played which concert," two tables have to be brought together in one query.
单独一张表只能回答关于它自己的问题,一旦问题需要"哪位艺人演了哪场演出",就必须在一条查询里把两张表结合起来。
Explainer
讲解
A3.3.1 introduced SELECT as one of the DML statements. This statement is about everything SELECT can actually DO once two tables are involved: combining them, filtering what comes back, matching text patterns, and putting the results in a sensible order.
A3.3.1 介绍了 SELECT 是 DML 语句之一。这条陈述讲的是,一旦涉及两张表,SELECT 实际上能做的一切:把它们结合起来、筛选返回的内容、匹配文本模式,并把结果排成合理的顺序。
A JOIN combines rows from two tables based on a matching column between them, usually a primary key in one table and the matching foreign key in the other. Without it, a query can only ever see one table at a time.
JOIN 根据两张表之间相匹配的列来合并它们的行,通常是一张表中的主键和另一张表中匹配的外键。没有它,一条查询每次只能看到一张表。
How a JOIN actually builds its result
JOIN 究竟是怎样构建出结果的
Not by magic, by checking one ID at a time against the other table, over and over.
不是靠魔法,而是一次一个 ID、反复地去另一张表里核对。
The command toolkit
命令工具箱
| Command | 命令 | What it does | 作用 | Example | 示例 |
|---|---|---|---|---|---|
| JOIN ... ON ... | Combines rows from two tables using a matching column. | 用相匹配的列合并两张表的行。 | SELECT * FROM Concert JOIN Artist ON Concert.ArtistID = Artist.ArtistID; | ||
| DISTINCT | Removes duplicate rows from the result, keeping only unique ones. | 从结果中去掉重复的行,只保留唯一的行。 | SELECT DISTINCT Genre FROM Artist; | ||
| WHERE | Filters individual rows before any grouping happens. | 在任何分组发生之前,筛选单独的行。 | SELECT * FROM Concert WHERE VenueName = "Blue Note Club"; | ||
| = <> > < >= <= | Relational operators: compare a field's value against a given value. | 关系运算符:把字段的值与给定的值作比较。 | SELECT * FROM Concert WHERE TicketPrice > 50; | ||
| BETWEEN ... AND ... | Filters values that fall within a range. | 筛选落在某个范围内的值。 | SELECT * FROM Concert WHERE TicketPrice BETWEEN 40 AND 80; | ||
| LIKE, with % and _ | Matches text against a pattern instead of an exact value. % stands in for any run of characters, however long, while _ stands in for one character and one only. | 用模式而不是精确的值来匹配文本。% 代表任意一串字符,不论多长,而 _ 代表一个字符,而且只代表一个。 | SELECT * FROM Concert WHERE VenueName LIKE "%Club"; | ||
| AND, OR, NOT | Combines or negates multiple conditions in a WHERE clause. | 在 WHERE 子句中组合或否定多个条件。 | SELECT * FROM Concert WHERE TicketPrice > 50 AND NOT VenueName = "Grand Arena"; | ||
| ORDER BY ... ASC / DESC | Sorts the result, ascending or descending, by one or more fields. | 按一个或多个字段对结果排序,升序或降序。 | SELECT * FROM Concert ORDER BY TicketPrice DESC; | ||
| GROUP BY | Collapses rows sharing a value into groups. | 把共享同一个值的行折叠成组。 | SELECT VenueName, COUNT(*) FROM Concert GROUP BY VenueName; | ||
| HAVING | Filters GROUPS after they've been formed, unlike WHERE, which filters rows before grouping. | 在组形成之后筛选组,不像 WHERE 是在分组之前筛选行。 | SELECT VenueName, COUNT(*) FROM Concert GROUP BY VenueName HAVING COUNT(*) > 1; |
Worked example
例题讲解
ARTIST and CONCERT: one command at a time
ARTIST 与 CONCERT:一次一条命令
Two tables, ARTIST and CONCERT, linked by ArtistID. Click through and watch the same two tables answer a different question at every step.
两张表,ARTIST 和 CONCERT,通过 ArtistID 相连。点击查看,同样的两张表在每一步回答一个不同的问题。
Try it yourself
动手试试
Run your own queries
运行你自己的查询
The same ARTIST and CONCERT tables, live. The command term for this statement is construct, and constructing means writing one yourself, not recognising one someone else wrote. Everything A3.3 teaches works here, not only this statement's own commands, so INSERT, UPDATE and DELETE run too and really do change the tables until you reset them.
同样的 ARTIST 和 CONCERT 两张表,可在线运行。这条陈述的指令词是 construct,而构建意味着自己动手写,而不是认出别人写好的。A3.3 教的一切都可以在这里使用,不只是这条陈述自己的命令,所以 INSERT、UPDATE 和 DELETE 也能运行,并且在你重置之前,确实会改变这些表。
4 rows
5 rows
Things worth trying. Write ArtistID on its own in a joined query and see why it has to be qualified. Swap HAVING for WHERE in the last example. Change LIKE "Dana%" to LIKE "%s" and work out why the results change. Each one is a real exam error, and triggering it yourself makes it stick.
值得尝试的事。在连接查询中单独写 ArtistID,看看为什么它必须加上限定。把最后一个例子中的 HAVING 换成 WHERE。把 LIKE "Dana%" 改成 LIKE "%s",想一想为什么结果会变。每一个都是真实的考试错误,亲手触发它会让你记得更牢。
Check your understanding
检查你的理解
A query needs to find only the venues that have hosted MORE THAN ONE concert. Which clause makes that filter possible?
一条查询需要找出只举办过不止一场演出的场地。哪个子句能做这个筛选?
Common mistake
常见错误
A3.3.2A3.3.2 的这一常见模式RecurringWHERE and HAVING both look like they "filter the query," and candidates often use them interchangeably. WHERE filters ROWS, before any grouping exists. HAVING filters GROUPS, after GROUP BY has already run, and it's the only one of the two that can reference an aggregate like COUNT(*) at all.
反复出现WHERE 和 HAVING 看起来都在"筛选查询",考生常常把它们混用。WHERE 筛选的是行,在任何分组存在之前。HAVING 筛选的是组,在 GROUP BY 已经运行之后,而且两者之中只有它能引用 COUNT(*) 这样的聚合函数。
What a weak answer looks like: "WHERE COUNT(*) > 1" to find venues with more than one concert. This is invalid, COUNT(*) doesn't exist yet at the point WHERE runs, grouping hasn't happened.
较弱的答案是这样的:"WHERE COUNT(*) > 1",用来找出举办过不止一场演出的场地。这是无效的,在 WHERE 运行的时候 COUNT(*) 还不存在,分组还没有发生。
What it should say: "GROUP BY VenueName HAVING COUNT(*) > 1", group the rows by venue first, THEN filter which groups survive based on how many rows ended up in each one.
应该这样写:"GROUP BY VenueName HAVING COUNT(*) > 1",先按场地对行分组,然后根据每一组最终有多少行来筛选哪些组留下来。
Linking question
联系性问题
How do programming languages interact with databases to store, retrieve and manipulate data?
编程语言如何与数据库交互,来存储、检索和操作数据?
A JOIN query like the ones on this page rarely runs on its own, a real application embeds it inside Python, Java or another high-level language, which sends the SQL string to the database, waits for the result set, then loops over it like any other collection. The SQL itself stays declarative (WHAT to retrieve), the surrounding program stays imperative (HOW to use what comes back).
像本页这样的 JOIN 查询很少单独运行,真实的应用程序会把它嵌入 Python、Java 或其他高级语言中,由后者把 SQL 字符串发送给数据库,等待结果集,然后像遍历任何其他集合一样遍历它。SQL 本身保持声明式(要检索什么),周围的程序保持命令式(怎样使用返回的结果)。
Revision questions
复习题
Past-paper style. Write an answer, then reveal the marking points and mark yourself.
仿真题风格。先写出你的答案,再显示评分要点并给自己打分。
[2]Construct a query that joins ARTIST and CONCERT to list every artist's name alongside the venue they played.
[2]构建一条查询,连接 ARTIST 和 CONCERT,列出每位艺人的名字以及他们演出的场地。
Marking points
评分要点
- A correct SELECT naming the two columns, for example Artist.Name and Concert.Venue.
- FROM Artist JOIN Concert ON Artist.ArtistID = Concert.ArtistID (foreign key matched to primary key).
- 一条正确的 SELECT,写出两个列,例如 Artist.Name 和 Concert.Venue。
- FROM Artist JOIN Concert ON Artist.ArtistID = Concert.ArtistID(外键匹配主键)。
[3]Construct a query that finds every artist whose name starts with "The".
[3]构建一条查询,找出名字以 "The" 开头的每一位艺人。
Marking points
评分要点
- SELECT * FROM Artist (or the name column).
- WHERE Name LIKE 'The%'.
- The % wildcard matches any characters after The, so every name beginning with The is returned.
- SELECT * FROM Artist(或选姓名列)。
- WHERE Name LIKE 'The%'。
- 通配符 % 匹配 The 之后的任意字符,所以每个以 The 开头的名字都会被返回。
[5]Construct a query that lists every concert with a TicketPrice between 40 and 80, ordered by TicketPrice in descending order. Explain why BETWEEN is inclusive of both boundary values.
[5]构建一条查询,列出 TicketPrice 在 40 到 80 之间的每一场演出,并按 TicketPrice 降序排列。解释为什么 BETWEEN 包含两个边界值。
Marking points
评分要点
- SELECT the concert rows FROM Concert.
- WHERE TicketPrice BETWEEN 40 AND 80.
- ORDER BY TicketPrice DESC.
- BETWEEN is inclusive because it is defined as TicketPrice >= 40 AND TicketPrice <= 80, so 40 and 80 both qualify.
- 从 Concert 表 SELECT 演出行。
- WHERE TicketPrice BETWEEN 40 AND 80。
- ORDER BY TicketPrice DESC。
- BETWEEN 包含端点,因为它被定义为 TicketPrice >= 40 AND TicketPrice <= 80,所以 40 和 80 都满足。
Flashcards
闪卡
Active recall for this statement's key terms.
针对本条陈述关键术语的主动回忆。
Keep this statement's practice with you
把本条陈述的练习带在身边
Free account: unlock every revision question and flashcard for A3.3.2, and every other IB CS 2027 statement.
免费账号:解锁 A3.3.2 以及其他所有 IB CS 2027 陈述的全部复习题和闪卡。