此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
选择列
SELECT * 返回每一列。通常你只想要其中几列。不用 *,而是列出你想要的列,用逗号隔开:
SELECT name, score FROM student;
结果就只有这些列,顺序和你写的一样。
用 AS 给列改名
你可以用 AS 给结果中的列改名。这不会改动表本身 —— 只改变显示的标题:
SELECT name AS pupil, score AS mark FROM student;
标题就变成了 pupil 和 mark。这对做清晰的报表很有用。
示例:列表的顺序即为获取数据的顺序
问题。 表格 student 包含字段 id、name、form 和 score。编写一个查询,显示每位学生的 班级(form),然后是其 姓名。
答案。 按照问题要求的顺序命名这两个字段:
SELECT form, name FROM student;
form | name
11A | Mei
11B | Jamal
11A | Sara
11B | Tom
11A | Lin
书写 SELECT name, form 会显示相同的数据,但列顺序相反,而问题要求先显示班级。
常见错误
- 遗漏逗号会重命名列。
SELECT name score FROM student会被解析为name AS score:你将得到一列名为score的列,其中包含姓名。每两个列之间必须加逗号。 - 最后一个列后没有逗号。
SELECT name, score, FROM student会导致语法错误。 AS仅更改结果中的标题。表格本身的字段名称保持不变。
探索
SELECT 选取列
Choosing columns keeps only the fields you name.
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
Select only the name and score columns from student, in that order.
点击“运行”查看此处输出。
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
Select name and score, but rename the headings to pupil and mark using AS.
点击“运行”查看此处输出。
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
Show each student's score 第一个, then their name. The starter lists the two columns the wrong way round: swap them.
点击“运行”查看此处输出。