Postgresql 中文操作指南

7.1. Overview #

从数据库检索数据的检索过程或命令称为 query 。在 SQL 中, SELECT 命令用于指定查询。 SELECT 的常规语法命令如下:

The process of retrieving or the command to retrieve data from a database is called a query. In SQL the SELECT command is used to specify queries. The general syntax of the SELECT command is

[WITH with_queries] SELECT select_list FROM table_expression [sort_specification]

以下部分描述了选择列表、表格表达式和排序规范的详细信息。WITH 查询作为高级功能,最后进行处理。

The following sections describe the details of the select list, the table expression, and the sort specification. WITH queries are treated last since they are an advanced feature.

简单类型的查询格式为:

A simple kind of query has the form:

SELECT * FROM table1;

假设有一个名为 table1 的表,则此命令将检索 table1 中的所有行和所有用户定义的列。(检索方法取决于客户端应用程序。例如,psql 程序将在屏幕上显示 ASCII 艺术表,而客户端库将提供用于从查询结果提取各个值的功能。)选择列表规范 * 表示表格表达式恰好提供的列。选择列表还可以选择可用列的子集或使用这些列进行计算。例如,如果 table1 具有名为 abc 的列(可能还有其他列),则可以进行以下查询:

Assuming that there is a table called table1, this command would retrieve all rows and all user-defined columns from table1. (The method of retrieval depends on the client application. For example, the psql program will display an ASCII-art table on the screen, while client libraries will offer functions to extract individual values from the query result.) The select list specification * means all columns that the table expression happens to provide. A select list can also select a subset of the available columns or make calculations using the columns. For example, if table1 has columns named a, b, and c (and perhaps others) you can make the following query:

SELECT a, b + c FROM table1;

(假设 bc 是数字数据类型)。有关更多详细信息,请参阅 Section 7.3

(assuming that b and c are of a numerical data type). See Section 7.3 for more details.

FROM table1 是表格表达式的一种简单类型:它只读取一张表。一般来说,表格表达式可以是基本表、联接和子查询的复杂结构。但是,您还可以完全忽略表格表达式,并使用 SELECT 命令作为计算器:

FROM table1 is a simple kind of table expression: it reads just one table. In general, table expressions can be complex constructs of base tables, joins, and subqueries. But you can also omit the table expression entirely and use the SELECT command as a calculator:

SELECT 3 * 4;

如果选择列表中的表达式返回不同的结果,则此方法更有用。例如,您可以这样调用函数:

This is more useful if the expressions in the select list return varying results. For example, you could call a function this way:

SELECT random();