成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

SELECT 中文man頁面

系統
SELECT 將從一個或更多表中返回記錄行。

NAME

SELECT - 從表或視圖中取出若干行

SYNOPSIS

SELECT [ ALL | DISTINCT [ ON ( expression [, ...] ) ] ]
    * | expression [ AS output_name ] [, ...]
    [ FROM from_item [, ...] ]
    [ WHERE condition ]
    [ GROUP BY expression [, ...] ]
    [ HAVING condition [, ...] ]
    [ { UNION | INTERSECT | EXCEPT } [ ALL ] select ]
    [ ORDER BY expression [ ASC | DESC | USING operator ] [, ...] ]
    [ LIMIT { count | ALL } ]
    [ OFFSET start ]
    [ FOR UPDATE [ OF table_name [, ...] ] ]

where from_item can be one of:

    [ ONLY ] table_name [ * ] [ [ AS ] alias [ ( column_alias [, ...] ) ] ]
    ( select ) [ AS ] alias [ ( column_alias [, ...] ) ]
    function_name ( [ argument [, ...] ] ) [ AS ] alias [ ( column_alias [, ...] | column_definition [, ...] ) ]
    function_name ( [ argument [, ...] ] ) AS ( column_definition [, ...] )
    from_item [ NATURAL ] join_type from_item [ ON join_condition | USING ( join_column [, ...] ) ]

[Comment: FIXME: This last syntax is incorrect if the join type is an INNER or OUTER join (in which case one of NATURAL, ON ..., or USING ... is mandatory, not optional). What's the best way to fix this?]  

DESCRIPTION 描述

SELECT 將從一個或更多表中返回記錄行。 SELECT 通常的處理如下:

1.

 計算列出在 FROM 中的所有元素。(FROM 中的每個元素都是一個真正的或者虛擬的表。)如果在 FROM 列表里聲明了多過一個元素,那么他們就交叉連接在一起。(參閱下面的 FROM Clause [select(7)] )。
2.

 如果聲明了 WHERE 子句,那么在輸出中消除所有 不滿足條件的行。(參閱下面的 WHERE Clause [select(7)] )。
3.

 如果聲明了 GROUP BY 子句,輸出就分成匹配一個或多個數值的不同組里。 如果出現了 HAVING 子句,那么它消除那些不滿足給出條件的組。(參閱下面的 GROUP BY Clause [select(7)] 和 HAVING Clause [select(7)] )。
4.

 使用 UNION,INTERSECT, 和 EXCEPT,我們可以把多個 SELECT  語句的輸出合并成一個結果集。UNION 操作符返回在兩個結果集或者其中一個中的行, INTERSECT 操作符返回嚴格地在兩個結果集中都有的行。 EXCEPT 操作符返回在第一個結果集中,但是不在第二個結果集中的行。不管哪種情況, 重復的行都被刪除,除非聲明了 ALL。(參閱下面的 UNION Clause [select(7)], INTERSECT Clause [select(l)], 和 EXCEPT Clause [select(7)] )。
5.

 實際輸出行的時候,SELECT 先為每個選出的行計算輸出表達式 (參閱下面的 SELECT List [select(7)] )。
6.

 如果聲明了 ORDER BY 子句,那么返回的行是按照指定的順序排序的。 如果沒有給出 ORDER BY,那么數據行是按照系統認為可以最快生成的方法給出的。 (參閱下面的  ORDER BY Clause [select(7)] )。
7.

 如果給出了 LIMIT 或者 OFFSET  子句,那么 SELECT 語句只返回結果行的一個子集。(參閱下面的 LIMIT Clause [select(7)] )。
8.
DISTINCT 從結果中刪除那些重復的行。 DISTINCT ON 刪除那些匹配所有指定表達式的行。 ALL (缺省)將返回所有候選行,包括重復的。 (參閱下面的 DISTINCT Clause [select(7)] )。
9.
FOR UPDATE 子句導致 SELECT 語句對并發的更新鎖住選定的行。(參閱下面的 FOR UPDATE Clause [select(7)] )。


 你必須有 SELECT 權限用來從表中讀取數值。 使用 FOR UPDATE 還要求 UPDATE 權限。  

PARAMETERS 參數

FROM 子句

FROM 子句為 SELECT 聲明一個或者多個源表。 如果聲明了多個源表,那么結果就是所有源表的笛卡兒積(交叉連接)。 但是通常我們會添加一些條件,把返回行限制成笛卡兒積的一個小的結果集。

FROM-子句可以包括:

table_name

 一個現存的表或視圖的名字(可以有模式修飾)。 如果聲明了ONLY,則只掃描該表。 如果沒有聲明ONLY,該表和所有其派生表(如果有的話)都被掃描。 可以在表名后面跟一個*來表示掃所有其后代表, 但在目前的版本里,這是缺省特性。 (在 PostgreSQL 7.1 以前的版本里,ONLY是缺省特性。) 缺省的特性可以通過修改配置選項 sql_interitance 來改變。
alias

 為那些包含別名的 FROM 項目取的別名。別名用于縮寫或者在自連接中消除歧義(自連接里,同一個表掃描了多次)。 如果提供了別名,那么它就會完全隱藏表或者函數的實際名字; 比如,如果給出 FROM foo AS f,那么 SELECT  剩下的東西必須吧這個 FROM 項以 f 而不是 foo 引用。如果寫了別名, 我們也可以提供一個字段別名列表,這樣可以替換表中一個或者多個字段的名字。
select

 一個子 SELECT 在 FROM 子句里出現的。 它的輸出作用好象是為這條 SELECT 命令在其生存期里創建一個臨時表。 請注意這個子 SELECT 必須用園括弧包圍。 并且必須給它加別名。
function_name

 函數調用可以出現在 FROM 子句里。 (對于那些返回結果集的函數特別有用,但是任何函數都能用。) 這么做就好像在這個 SELECT 命令的生命期中, 把函數的輸出創建為一個臨時表一樣。我們也可以使用別名。如果寫了別名, 我們還可以寫一個字段別名列表,為函數返回的復合類型的一個或多個屬性提供名字替換。 如果函數定義為了 record 數據類型, 那么必須出現一個 AS 關鍵字或者別名,后面跟著一個字段定義列表, 形如:( column_name data_type [, ... ])。 這個字段定義列表必須匹配函數返回的字段的實際數目和類型。
join_type
*
[ INNER ] JOIN
*
LEFT [ OUTER ] JOIN
*
RIGHT [ OUTER ] JOIN
*
FULL [ OUTER ] JOIN
*
CROSS JOIN


 之一。 就 INNER 和 OUTER 連接類型, 我們必須聲明一個連接條件,也就是說一個 NATURAL, ON join_condition, 或者 USING (join_column [, ...])。 見下文獲取它們的含義,對于 CROSS JOIN,這些子句都不能出現。


 一個 JOIN 子句,組合了兩個 FROM 項。 必要時使用圓括弧以決定嵌套的順序。 如果沒有圓括弧,JOIN 的嵌套從左向右。 在任何情況下,JOIN 都比逗號分隔的 FROM 項綁定得更緊。

CROSS JOIN 和 INNER JOIN 生成一個簡單的笛卡兒積,和你在 FROM 的頂層列出兩個項的結果相同。 CROSS JOIN 等效于 INNER JOIN ON (true), 也就是說,沒有被條件刪除的行。這種連接類型只是符號上的方便, 因為它們和你用簡單的 FROM 和 WHERE 干的事情是一樣的。

LEFT OUTER JOIN 返回有條件的笛卡兒積(也就是說, 所有組合出來的行都通過了連接條件)中的行,加上左手邊的表中沒有對應的右手邊表的行可以一起匹配通過連接條件的那些行。 這樣的左手邊的行擴展成連接生成表的全長,方法是在那些右手邊表對應的字段位置填上空。請注意,只有在決定那些行是匹配的時候, 之計算 JOIN 子句自己的條件。外層的條件是在這之后施加的。


 對應的是,RIGHT OUTER JOIN 返回所有連接出來的行, 加上每個不匹配的右手邊行(左邊用空值擴展)。這只是一個符號上的便利,因為我們總是可以把它轉換成一個 LEFT OUTER JOIN, 只要把左邊和右邊的輸入對掉一下即可。

FULL OUTER JOIN 返回所有連接出來的行,加上每個不匹配的左手邊的行(右邊用空值擴展), 加上每個不匹配的右手邊的行(左邊用空值擴展)。

ON join_condition
join_condition 是一個表達式, 生成類型為 boolean 的結果(類似WHERE 子句), 表示連接中那些行被認為是匹配的。
USING (join_column [, ...])

 一個形如 USING ( a, b, ... ) 的子句, 是ON left_table.a = right_table.a AND left_table.b = right_table.b ...  的縮寫。同樣,USING 蘊涵著:每對等效字段中只有一個包含在連接輸出中,而不是兩個都輸出的意思。
NATURAL
NATURAL 是一個 USING 列表的縮寫,這個列表說的是兩個表中同名的的字段。

WHERE 子句


 可選的 WHERE 條件有如下常見的形式:

WHERE condition


 這里 condition  可以是任意生成類型為 boolean 的表達式。 任何不滿足這個條件的行都會從輸出中刪除。如果一個行的數值替換到條件的引用中計算出來的條件為真,那么該行就算滿足條件。  

GROUP BY 子句


 可選的 GROUP BY 子句的一般形式

GROUP BY expression [, ...]

GROUP BY 將把所有在組合了的表達式上共享同樣的值的行壓縮成一行。 expression 可以是一個輸入字段名字, 或者是一個輸入字段(SELECT 列表)的序號,或者也可以是任意從輸入字段值形成的任意表達式。 在有歧義的情況下,一個 GROUP BY 的名字將被解釋成輸入字段的名字,而不是輸出字段的名字。


 如果使用了聚集函數,那么就會對組成一組的所有行進行計算,為每個組生成一個獨立的值(而如果沒有 GROUP BY, 那么聚集對選出來的所有行計算出一個值)。如果出現了 GROUP BY, 那么 SELECT 列表表達式中再引用那些沒有分組的字段就是非法的, 除非放在聚集函數里,因為對于未分組的字段,可能會返回多個數值。  

HAVING 子句


 可選的 HAVING 子句有如下形式:

HAVING condition


 這里 condition  和為 WHERE 子句里聲明的相同。

HAVING 去除了一些不滿足條件的組行。 HAVING 與 WHERE 不同: WHERE 在使用 GROUP BY 之前過濾出單獨的行,而 HAVING 過濾由 GROUP BY 創建的行。 在 condition 里引用的每個字段都必須無歧義地引用一個分組的行,除非引用出現在一個聚集函數里。  

UNION 子句

UNION 子句的一般形式是:

select_statement UNION [ ALL ] select_statement


 這里 select_statement 是任意沒有 ORDER BY,LIMIT,或者 FOR UPDATE 子句的 SELECT語句。 (如果用圓括弧包圍,ORDER BY 和 LIMIT 可以附著在子表達式里。 如果沒有圓括弧,這些子句將交給 UNION 的結果使用, 而不是給它們右手邊的輸入表達式。)

UNION 操作符計算那些涉及到的所有 SELECT 語句返回的行的結果聯合。 一個行如果至少在兩個結果集中的一個里面出現,那么它就會在這兩個結果集的集合聯合中。 兩個做為 UNION 直接操作數的SELECT必須生成相同數目的字段, 并且對應的字段必須有兼容的數據類型。


 缺省地,UNION 的結果不包含任何重復的行,除非聲明了 ALL 子句。 ALL 制止了消除重復的動作。


 同一SELECT語句中的多個 UNION 操作符是從左向右計算的, 除非用圓括弧進行了標識。


 目前,FOR UPDATE 不能在 UNION 的結果或輸入中聲明。  

INTERSECT 子句

INTERSECT 子句的一般形式是:

select_statement INTERSECT [ ALL ] select_statement

select_statement 是任何不帶 ORDER BY, LIMIT,或者 FOR UPDATE 子句的 SELECT 語句。


 INTERSECT 計算涉及的 SELECT 語句返回的行的集合交集。 如果一個行在兩個結果集中都出現,那么它就在兩個結果集的交集中。


 NTERSECT 的結果不包含任何重復行,除非你聲明了 ALL 選項。 用了 ALL 以后,一個在左手邊的表里有 m 個重復而在右手邊表里有 n 個重復的行將出現 min(m,n) 次。


 除非用圓括號指明順序, 同一 SELECT 語句中的多個 INTERSECT 操作符是從左向右計算的。 INTERSECT 比 UNION 綁定得更緊 --- 也就是說 A UNION B INTERSECT C 將讀做 A UNION (B INTERSECT C),除非你用圓括弧聲明。  

EXCEPT 子句

EXCEPT 子句有如下的通用形式:

select_statement EXCEPT [ ALL ] select_statement


 這里 fIselect_statement 是任何沒有 ORDER BY,LIMIT,或者 FOR UPDATE  子句的 SELECT 表達式。

EXCEPT 操作符計算存在于左邊SELECT 語句的輸出而不存在于右邊語句輸出的行。

EXCEPT 的結果不包含任何重復的行,除非聲明了 ALL 選項。 使用 ALL 時,一個在左手邊表中有 m 個重復而在右手邊表中有 n 個重復的行將出現 max(m-n,0) 次。


 除非用圓括弧指明順序,同一 SELECT 語句中的多個 EXCEPT 操作符是從左向右計算的。 EXCEPT 和 UNION 綁定級別相同。  

SELECT 列表

SELECT 列表(在關鍵字 SELECT 和 FROM) 之間的東西)聲明一個表達式,這個表達式形成 SELECT 語句的輸出行。這個表達式可以(通常也的確是)引用那些在 FROM 子句里計算的字段。 通過使用 AS output_name, 我們可以為一個輸出行聲明另外一個名字。這個名字主要用做顯示該行的標簽。 它也可以在 ORDER BY 和 GROUP BY 子句里當作字段值的引用, 但是不能在 WHERE 或者 HAVING 子句里這么用;在那里,你必須寫出表達式。


 除了表達式之外,我們也可以在輸出列表上寫一個 * 表示選出的行的所有字段的縮寫。同樣,我們可以寫 table_name.*  作為來自某個特定表的字段的縮寫。  

ORDER BY 子句


 可選的 ORDER BY 子句有下面的一般形式:

ORDER BY expression [ ASC | DESC | USING operator ] [, ...]

expression 可以是一個輸出字段(SELECT 列表)的名字或者序號, 或者也可以是用輸入字段的數值組成的任意表達式。

ORDER BY 子句導致結果行根據指定的表達式進行排序。 如果根據最左邊的表達式,兩行的結果相同,那么就根據下一個表達式進行比較, 依此類推。如果對于所有聲明的表達式他們都相同,那么以隨機順序返回。


 序數指的是列/字段按順序(從左到右)的位置。 這個特性讓我們可以對沒有唯一名稱的列/字段進行排序。 這一點從來不是必須的, 因為總是可以通過 AS 子句給一個要計算的列/字段賦予一個名稱。


 在 ORDER BY 里還可以使用任意表達式, 包括那些沒有出現在SELECT結果列表里面的字段。 因此下面的語句現在是合法的:

SELECT name FROM distributors ORDER BY code;


 這個特性的一個局限就是應用于 UNION,INTERSECT, 或者 EXCEPT 查詢的 ORDER BY 子句只能在一個輸出字段名或者數字上聲明,而不能在一個表達式上聲明。


 請注意如果一個 ORDER BY 表達式是一個簡單名稱, 同時匹配結果字段和輸入字段, ORDER BY 將把它解釋成結果字段名稱。 這和 GROUP BY 在同樣情況下做的選擇正相反。 這樣的不一致是由 SQL 標準強制的。


 我們可以給 ORDER BY 子句里每個列/字段加一個關鍵字 DESC (降序)或 ASC(升序)。如果不聲明, ASC 是缺省。 我們還可以在 USING 子句里聲明一個排序操作符來實現排序。 ASC 等效于使用 USING < 而 DESC 等效于使用 USING >。 (But the creator of a user-defined data type can define exactly what the default sort ordering is, and it might correspond to operators with other names.)


 在一個域里,空值排序時排在其它數值前面。換句話說,升序排序時, 空值排在末尾,而降序排序時空值排在開頭。


 字符類型的數據是按照區域相關的字符集順序排序的,這個區域是在數據庫集群初始化的時候建立的。  

LIMIT 子句

LIMIT 子句由兩個獨立的子句組成:

LIMIT { count | ALL }
OFFSET start


 這里 count 聲明返回的最大行數,而 start 聲明開始返回行之前忽略的行數。
 .PP
  LIMIT 允許你檢索由查詢其他部分生成的行的某一部分。 如果給出了限制計數,那么返回的行數不會超過哪個限制。 如果給出了一個偏移量,那么開始返回行之前會忽略那個數量的行。


 在使用 LIMIT 時, 一個好習慣是使用一個 ORDER BY 子句把結果行限制成一個唯一的順序。 否則你會得到無法預料的查詢返回的子集 --- 你可能想要第十行到第二十行, 但以什么順序?除非你聲明 ORDER BY,否則你不知道什么順序。


 查詢優化器在生成查詢規劃時把 LIMIT 考慮進去了, 所以你很有可能因給出的 LIMIT 和 OFFSET 值不同而得到不同的規劃(生成不同的行序)。 因此用不同的 LIMIT/OFFSET 值選擇不同的查詢結果的子集將不會產生一致的結果, 除非你用 ORDER BY 強制生成一個可預計的結果順序。 這可不是毛病;這是 SQL 生來的特點,因為除非用了 ORDER BY 約束順序, SQL 不保證查詢生成的結果有任何特定的順序。  

DISTINCT 子句


 如果聲明了 DISTINCT,那么就從結果集中刪除所有重復的行(每個有重復的組都保留一行)。 ALL 聲明相反的作用:所有行都被保留;這個是缺省。

DISTINCT ON ( expression [, ...] ) 只保留那些在給出的表達式上運算出相同結果的行集合中的第一行。 DISTINCT ON 表達式是使用與 ORDER BY (見上文) 相同的規則進行解釋的。請注意,除非我們使用了 ORDER BY 來保證我們需要的行首先出現,否則,每個 "第一行" 是不可預測的。 比如,

SELECT DISTINCT ON (location) location, time, report
    FROM weather_reports
    ORDER BY location, time DESC;


 為每個地點檢索最近的天氣報告。但是如果我們沒有使用 ORDER BY  來強制對每個地點的時間值進行降序排序,那么我們就會得到每個地點的不知道什么時候的報告。


 DISTINCT ON 表達式必須匹配最左邊的 ORDER BY 表達式。 ORDER BY 子句將通常包含額外的表達式來判斷每個 DISTINCT ON 組里面需要的行的優先級。  

FOR UPDATE 子句

FOR UPDATE 子句有下面的形式

FOR UPDATE [ OF table_name [, ...] ]

FOR UPDATE 令那些被 SELECT 語句檢索出來的行被鎖住,就像要更新一樣。 這樣就避免它們在當前事務結束前被其它事務修改或者刪除; 也就是說,其它視圖 UPDATE,DELETE, 或者 SELECT FOR UPDATE 這些行的事務將被阻塞, 直到當前事務結束。同樣,如果一個來自其它事務的 UPDATE, DELETE,或者 SELECT FOR UPDATE 已經鎖住了某個或某些選定的行,SELECT FOR UPDATE 將等到那些事務結束, 并且將隨后鎖住并返回更新的行(或者不返回行,如果行已經被刪除)。更多的討論參閱 Chapter 12 ``Concurrency Control'' 。


 如果特定的表在 FOR UPDATE 中,那么只有來自這些表中的行才被鎖住; 任何在 SELECT 中使用的其它表都只是和平常一樣讀取。

FOR UPDATE 不能在那些無法使用獨立的表數據行清晰標識返回行的環境里; 比如,它不能和聚集一起使用。

FOR UPDATE 可以在 LIMIT 前面出現, 主要是為了和 7.3 之前的 PostgreSQL 兼容。 不過,它在 LIMIT 后面執行更高效,因此我們建議放在 LIMIT 后面。  

EXAMPLES 例子


 將表 films 和表 distributors 連接在一起:

SELECT f.title, f.did, d.name, f.date_prod, f.kind
    FROM distributors d, films f
    WHERE f.did = d.did

       title       | did |     name     | date_prod  |   kind
-------------------+-----+--------------+------------+----------
 The Third Man     | 101 | British Lion | 1949-12-23 | Drama
 The African Queen | 101 | British Lion | 1951-08-11 | Romantic
 ...


 統計用kind 分組的所有電影和組的列/字段的 len(長度)的和:

SELECT kind, sum(len) AS total FROM films GROUP BY kind;

   kind   | total
----------+-------
 Action   | 07:34
 Comedy   | 02:58
 Drama    | 14:28
 Musical  | 06:42
 Romantic | 04:38


 統計所有電影(films),組的列/字段 len(長度)的和,用 kind 分組并且顯示小于5小時的組總和:

SELECT kind, sum(len) AS total
    FROM films
    GROUP BY kind
    HAVING sum(len) < interval '5 hours';

   kind   | total
----------+-------
 Comedy   | 02:58
 Romantic | 04:38


 下面兩個例子是根據第二列(name)的內容對單獨的結果排序的經典的方法:

SELECT * FROM distributors ORDER BY name;
SELECT * FROM distributors ORDER BY 2;

 did |       name
-----+------------------
 109 | 20th Century Fox
 110 | Bavaria Atelier
 101 | British Lion
 107 | Columbia
 102 | Jean Luc Godard
 113 | Luso films
 104 | Mosfilm
 103 | Paramount
 106 | Toho
 105 | United Artists
 111 | Walt Disney
 112 | Warner Bros.
 108 | Westward


 下面這個例子演示如何獲得表 distributors 和 actors的連接, 只將每個表中以字母 W 開頭的取出來。 因為只取了不相關的行,所以關鍵字 ALL 被省略了:

distributors:               actors:
 did |     name              id |     name
-----+--------------        ----+----------------
 108 | Westward               1 | Woody Allen
 111 | Walt Disney            2 | Warren Beatty
 112 | Warner Bros.           3 | Walter Matthau
 ...                         ...

SELECT distributors.name
    FROM distributors
    WHERE distributors.name LIKE 'W%'
UNION
SELECT actors.name
    FROM actors
    WHERE actors.name LIKE 'W%';

      name
----------------
 Walt Disney
 Walter Matthau
 Warner Bros.
 Warren Beatty
 Westward
 Woody Allen


 這個例子顯示了如何在 FROM 子句中使用一個函數, 包括帶有和不帶字段定義列表的。

CREATE FUNCTION distributors(int) RETURNS SETOF distributors AS '
    SELECT * FROM distributors WHERE did = $1;

SELECT * FROM distributors(111);
 did |    name
-----+-------------
 111 | Walt Disney

CREATE FUNCTION distributors_2(int) RETURNS SETOF record AS '
    SELECT * FROM distributors WHERE did = $1;

SELECT * FROM distributors_2(111) AS (f1 int, f2 text);
 f1  |     f2
-----+-------------
 111 | Walt Disney

COMPATIBILITY 兼容性


 當然,SELECT 語句和 SQL 標準兼容。但是還有一些擴展和一些缺少的特性。  

省略 FROM 子句

PostgreSQL 允許我們在一個查詢里省略 FROM 子句。 它的最直接用途就是計算簡單的常量表達式的結果:

SELECT 2+2;

 ?column?
----------
        4


 其它有些 SQL 數據庫不能這么做,除非引入一個單行的偽表做 SELECT 的數據源。


 這個特性的另外一個不太明顯的用途是把一個普通的從一個或多個表的 SELECT 縮寫:

SELECT distributors.* WHERE distributors.name = 'Westward';

 did |   name
-----+----------
 108 | Westward

這樣也可以運行是因為我們給 SELECT 中引用了但沒有在 FROM 中提到的每個表都加了一個隱含的 FROM 項。


 盡管這是個很方便的寫法,但它卻容易誤用。 比如,下面的查詢

SELECT distributors.* FROM distributors d;

可能就是個錯誤;用戶最有可能的意思是

SELECT d.* FROM distributors d;

而不是下面的他實際上得到的無約束的連接

SELECT distributors.* FROM distributors d, distributors distributors;

為了幫助檢測這種錯誤, PostgreSQL 以及以后的版本將在你使用一條即有隱含 FROM 特性又有明確的 FROM 子句的查詢的時候給出警告。 Also, it is possible to disable the implicit-FROM feature by setting the ADD_MISSING_FROM parameter to false.  

AS 關鍵字


 在 SQL 標準里,可選的關鍵字 AS 是多余的,可以忽略掉而不對語句產生任何影響。 PostgreSQL 分析器在重命名列/字段時需要這個關鍵字, 因為類型擴展的特性會導致在這個環境里的歧義。 不過,AS 在 FROM 項里是可選的。  

GROUP BY 和 ORDER BY 里可用的名字空間


 在 SQL92 標準里,ORDER BY 子句只能使用結果字段名或者編號, 而 GROUP BY 子句只能用基于輸入字段名的表達式。 PostgreSQL 對這兩個子句都進行了擴展, 允許另外一種選擇(但是如果存在歧義,則使用標準的解釋)。 PostgreSQL 還允許兩個子句聲明任意的表達式。 請注意在表達式中出現的名字強總是被當作輸入字段名,而不是結果字段名。

SQL99 uses a slightly different definition which is not upward compatible with SQL92. In most cases, however, PostgreSQL will interpret an ORDER BY or GROUP BY expression the same way SQL99 does.  

非標準子句

DISTINCT ON, LIMIT, 和 OFFSET 都沒有在 SQL 標準中定義。  

#p#

NAME

SELECT - retrieve rows from a table or view

SYNOPSIS

SELECT [ ALL | DISTINCT [ ON ( expression [, ...] ) ] ]
    * | expression [ AS output_name ] [, ...]
    [ FROM from_item [, ...] ]
    [ WHERE condition ]
    [ GROUP BY expression [, ...] ]
    [ HAVING condition [, ...] ]
    [ { UNION | INTERSECT | EXCEPT } [ ALL ] select ]
    [ ORDER BY expression [ ASC | DESC | USING operator ] [, ...] ]
    [ LIMIT { count | ALL } ]
    [ OFFSET start ]
    [ FOR UPDATE [ OF table_name [, ...] ] ]

where from_item can be one of:

    [ ONLY ] table_name [ * ] [ [ AS ] alias [ ( column_alias [, ...] ) ] ]
    ( select ) [ AS ] alias [ ( column_alias [, ...] ) ]
    function_name ( [ argument [, ...] ] ) [ AS ] alias [ ( column_alias [, ...] | column_definition [, ...] ) ]
    function_name ( [ argument [, ...] ] ) AS ( column_definition [, ...] )
    from_item [ NATURAL ] join_type from_item [ ON join_condition | USING ( join_column [, ...] ) ]

[Comment: FIXME: This last syntax is incorrect if the join type is an INNER or OUTER join (in which case one of NATURAL, ON ..., or USING ... is mandatory, not optional). What's the best way to fix this?]  

DESCRIPTION

SELECT retrieves rows from one or more tables. The general processing of SELECT is as follows:

1.
All elements in the FROM list are computed. (Each element in the FROM list is a real or virtual table.) If more than one element is specified in the FROM list, they are cross-joined together. (See FROM Clause [select(7)] below.)
2.
If the WHERE clause is specified, all rows that do not satisfy the condition are eliminated from the output. (See WHERE Clause [select(7)] below.)
3.
If the GROUP BY clause is specified, the output is divided into groups of rows that match on one or more values. If the HAVING clause is present, it eliminates groups that do not satisfy the given condition. (See GROUP BY Clause [select(7)] and HAVING Clause [select(7)] below.)
4.
Using the operators UNION, INTERSECT, and EXCEPT, the output of more than one SELECT statement can be combined to form a single result set. The UNION operator returns all rows that are in one or both of the result sets. The INTERSECT operator returns all rows that are strictly in both result sets. The EXCEPT operator returns the rows that are in the first result set but not in the second. In all three cases, duplicate rows are eliminated unless ALL is specified. (See UNION Clause [select(7)], INTERSECT Clause [select(l)], and EXCEPT Clause [select(7)] below.)
5.
The actual output rows are computed the SELECT output expressions for each selected row. (See SELECT List [select(7)] below.)
6.
If the ORDER BY clause is specified, the returned rows are sorted in the specified order. If ORDER BY is not given, the rows are returned in whatever order the system finds fastest to produce. (See ORDER BY Clause [select(7)] below.)
7.
If the LIMIT or OFFSET clause is specified, the SELECT statement only returns a subset of the result rows. (See LIMIT Clause [select(7)] below.)
8.
DISTINCT eliminates duplicate rows from the result. DISTINCT ON eliminates rows that match on all the specified expressions. ALL (the default) will return all candidate rows, including duplicates. (See DISTINCT Clause [select(7)] below.)
9.
The FOR UPDATE clause causes the SELECT statement to lock the selected rows against concurrent updates. (See FOR UPDATE Clause [select(7)] below.)

You must have SELECT privilege on a table to read its values. The use of FOR UPDATE requires UPDATE privilege as well.  

PARAMETERS

FROM CLAUSE

The FROM clause specifies one or more source tables for the SELECT. If multiple sources are specified, the result is the Cartesian product (cross join) of all the sources. But usually qualification conditions are added to restrict the returned rows to a small subset of the Cartesian product.

FROM-clause elements can contain:

table_name
The name (optionally schema-qualified) of an existing table or view. If ONLY is specified, only that table is scanned. If ONLY is not specified, the table and all its descendant tables (if any) are scanned. * can be appended to the table name to indicate that descendant tables are to be scanned, but in the current version, this is the default behavior. (In releases before 7.1, ONLY was the default behavior.) The default behavior can be modified by changing the sql_interitance configuration option.
alias
A substitute name for the FROM item containing the alias. An alias is used for brevity or to eliminate ambiguity for self-joins (where the same table is scanned multiple times). When an alias is provided, it completely hides the actual name of the table or function; for example given FROM foo AS f, the remainder of the SELECT must refer to this FROM item as f not foo. If an alias is written, a column alias list can also be written to provide substitute names for one or more columns of the table.
select
A sub-SELECT can appear in the FROM clause. This acts as though its output were created as a temporary table for the duration of this single SELECT command. Note that the sub-SELECT must be surrounded by parentheses, and an alias must be provided for it.
function_name
Function calls can appear in the FROM clause. (This is especially useful for functions that return result sets, but any function can be used.) This acts as though its output were created as a temporary table for the duration of this single SELECT command. An alias may also be used. If an alias is written, a column alias list can also be written to provide substitute names for one or more attributes of the function's composite return type. If the function has been defined as returning the record data type, then an alias or the key word AS must be present, followed by a column definition list in the form ( column_name data_type [, ... ] ). The column definition list must match the actual number and types of columns returned by the function.
join_type
One of
*
[ INNER ] JOIN
*
LEFT [ OUTER ] JOIN
*
RIGHT [ OUTER ] JOIN
*
FULL [ OUTER ] JOIN
*
CROSS JOIN

For the INNER and OUTER join types, a join condition must be specified, namely exactly one of NATURAL, ON join_condition, or USING (join_column [, ...]). See below for the meaning. For CROSS JOIN, none of these clauses may appear.

A JOIN clause, combines two FROM items. (Use parentheses if necessary to determine the order of nesting.)

CROSS JOIN and INNER JOIN produce a simple Cartesian product, the same as you get from listing the two items at the top level of FROM. CROSS JOIN is equivalent to INNER JOIN ON (true), that is, no rows are removed by qualification. These join types are just a notational convenience, since they do nothing you couldn't do with plain FROM and WHERE.

LEFT OUTER JOIN returns all rows in the qualified Cartesian product (i.e., all combined rows that pass its join condition), plus one copy of each row in the left-hand table for which there was no right-hand row that passed the join condition. This left-hand row is extended to the full width of the joined table by inserting null values for the right-hand columns. Note that only the JOIN clauses own condition is considered while deciding which rows have matches. Outer conditions are applied afterwards.

Conversely, RIGHT OUTER JOIN returns all the joined rows, plus one row for each unmatched right-hand row (extended with nulls on the left). This is just a notational convenience, since you could convert it to a LEFT OUTER JOIN by switching the left and right inputs.

FULL OUTER JOIN returns all the joined rows, plus one row for each unmatched left-hand row (extended with nulls on the right), plus one row for each unmatched right-hand row (extended with nulls on the left).

ON join_condition
join_condition is an expression resulting in a value of type boolean (similar to a WHERE clause) that specifies which rows in a join are considered to match.
USING (join_column [, ...])
A clause of the form USING ( a, b, ... ) is shorthand for ON left_table.a = right_table.a AND left_table.b = right_table.b .... Also, USING implies that only one of each pair of equivalent columns will be included in the join output, not both.
NATURAL
NATURAL is shorthand for a USING list that mentions all columns in the two tables that have the same names.

WHERE CLAUSE

The optional WHERE clause has the general form

WHERE condition

where condition is any expression that evaluates to a result of type boolean. Any row that does not satisfy this condition will be eliminated from the output. A row satisfies the condition if it returns true when the actual row values are substituted for any variable references.  

GROUP BY CLAUSE

The optional GROUP BY clause has the general form

GROUP BY expression [, ...]

GROUP BY will condense into a single row all selected rows that share the same values for the grouped expressions. expression can be an input column name, or the name or ordinal number of an output column (SELECT list), or it can be an arbitrary expression formed from input-column values. In case of ambiguity, a GROUP BY name will be interpreted as an input-column name rather than an output column name.

Aggregate functions, if any are used, are computed across all rows making up each group, producing a separate value for each group (whereas without GROUP BY, an aggregate produces a single value computed across all the selected rows). When GROUP BY is present, it is not valid for the SELECT list expressions to refer to ungrouped columns except within aggregate functions, since there would be more than one possible value to return for an ungrouped column.  

HAVING CLAUSE

The optional HAVING clause has the general form

HAVING condition

where condition is the same as specified for the WHERE clause.

HAVING eliminates group rows that do not satisfy the condition. HAVING is different from WHERE: WHERE filters individual rows before the application of GROUP BY, while HAVING filters group rows created by GROUP BY. Each column referenced in condition must unambiguously reference a grouping column, unless the reference appears within an aggregate function.  

UNION CLAUSE

The UNION clause has this general form:

select_statement UNION [ ALL ] select_statement

select_statement is any SELECT statement without an ORDER BY, LIMIT, or FOR UPDATE clause. (ORDER BY and LIMIT can be attached to a subexpression if it is enclosed in parentheses. Without parentheses, these clauses will be taken to apply to the result of the UNION, not to its right-hand input expression.)

The UNION operator computes the set union of the rows returned by the involved SELECT statements. A row is in the set union of two result sets if it appears in at least one of the result sets. The two SELECT statements that represent the direct operands of the UNION must produce the same number of columns, and corresponding columns must be of compatible data types.

The result of UNION does not contain any duplicate rows unless the ALL option is specified. ALL prevents elimination of duplicates.

Multiple UNION operators in the same SELECT statement are evaluated left to right, unless otherwise indicated by parentheses.

Currently, FOR UPDATE may not be specified either for a UNION result or for the inputs of UNION.  

INTERSECT CLAUSE

The INTERSECT clause has this general form:

select_statement INTERSECT [ ALL ] select_statement

select_statement is any SELECT statement without an ORDER BY, LIMIT, or FOR UPDATE clause.

The INTERSECT operator computes the set intersection of the rows returned by the involved SELECT statements. A row is in the intersection of two result sets if it appears in both result sets.

The result of INTERSECT does not contain any duplicate rows unless the ALL option is specified. With ALL, a row that has m duplicates in the left table and n duplicates in the right table will appear min(m,n) times in the result set.

Multiple INTERSECT operators in the same SELECT statement are evaluated left to right, unless parentheses dictate otherwise. INTERSECT binds more tightly than UNION. That is, A UNION B INTERSECT C will be read as A UNION (B INTERSECT C).  

EXCEPT CLAUSE

The EXCEPT clause has this general form:

select_statement EXCEPT [ ALL ] select_statement

select_statement is any SELECT statement without an ORDER BY, LIMIT, or FOR UPDATE clause.

The EXCEPT operator computes the set of rows that are in the result of the left SELECT statement but not in the result of the right one.

The result of EXCEPT does not contain any duplicate rows unless the ALL option is specified. With ALL, a row that has m duplicates in the left table and n duplicates in the right table will appear max(m-n,0) times in the result set.

Multiple EXCEPT operators in the same SELECT statement are evaluated left to right, unless parentheses dictate otherwise. EXCEPT binds at the same level as UNION.  

SELECT LIST

The SELECT list (between the key words SELECT and FROM) specifies expressions that form the output rows of the SELECT statement. The expressions can (and usually do) refer to columns computed in the FROM clause. Using the clause AS output_name, another name can be specified for an output column. This name is primarily used to label the column for display. It can also be used to refer to the column's value in ORDER BY and GROUP BY clauses, but not in the WHERE or HAVING clauses; there you must write out the expression instead.

Instead of an expression, * can be written in the output list as a shorthand for all the columns of the selected rows. Also, one can write table_name.* as a shorthand for the columns coming from just that table.  

ORDER BY CLAUSE

The optional ORDER BY clause has this general form:

ORDER BY expression [ ASC | DESC | USING operator ] [, ...]

expression can be the name or ordinal number of an output column (SELECT list), or it can be an arbitrary expression formed from input-column values.

The ORDER BY clause causes the result rows to be sorted according to the specified expressions. If two rows are equal according to the leftmost expression, the are compared according to the next expression and so on. If they are equal according to all specified expressions, they are returned in random order.

The ordinal number refers to the ordinal (left-to-right) position of the result column. This feature makes it possible to define an ordering on the basis of a column that does not have a unique name. This is never absolutely necessary because it is always possible to assign a name to a result column using the AS clause.

It is also possible to use arbitrary expressions in the ORDER BY clause, including columns that do not appear in the SELECT result list. Thus the following statement is valid:

SELECT name FROM distributors ORDER BY code;

A limitation of this feature is that an ORDER BY clause applying to the result of a UNION, INTERSECT, or EXCEPT clause may only specify an output column name or number, not an expression.

If an ORDER BY expression is a simple name that matches both a result column name and an input column name, ORDER BY will interpret it as the result column name. This is the opposite of the choice that GROUP BY will make in the same situation. This inconsistency is made to be compatible with the SQL standard.

Optionally one may add the key word ASC (ascending) or DESC (descending) after each expression in the ORDER BY clause. If not specified, ASC is assumed by default. Alternatively, a specific ordering operator name may be specified in the USING clause. ASC is usually equivalent to USING < and DESC is usually equivalent to USING >. (But the creator of a user-defined data type can define exactly what the default sort ordering is, and it might correspond to operators with other names.)

The null value sorts higher than any other value. In other words, with ascending sort order, null values sort at the end, and with descending sort order, null values sort at the beginning.

Character-string data is sorted according to the locale-specific collation order that was established when the database cluster was initialized.  

LIMIT CLAUSE

The LIMIT clause consists of two independent clauses:

LIMIT { count | ALL }
OFFSET start

count specifies the maximum number of rows to return, and start specifies the number of rows to skip before starting to return rows.

When using LIMIT, it is a good idea to use an ORDER BY clause that constrains the result rows into a unique order. Otherwise you will get an unpredictable subset of the query's rows---you may be asking for the tenth through twentieth rows, but tenth through twentieth in what ordering? You don't know what ordering unless you specify ORDER BY.

The query planner takes LIMIT into account when generating a query plan, so you are very likely to get different plans (yielding different row orders) depending on what you use for LIMIT and OFFSET. Thus, using different LIMIT/OFFSET values to select different subsets of a query result will give inconsistent results unless you enforce a predictable result ordering with ORDER BY. This is not a bug; it is an inherent consequence of the fact that SQL does not promise to deliver the results of a query in any particular order unless ORDER BY is used to constrain the order.  

DISTINCT CLAUSE

If DISTINCT is specified, all duplicate rows are removed from the result set (one row is kept from each group of duplicates). ALL specifies the opposite: all rows are kept; that is the default.

DISTINCT ON ( expression [, ...] ) keeps only the first row of each set of rows where the given expressions evaluate to equal. The DISTINCT ON expressions are interpreted using the same rules as for ORDER BY (see above). Note that the ``first row'' of each set is unpredictable unless ORDER BY is used to ensure that the desired row appears first. For example,

SELECT DISTINCT ON (location) location, time, report
    FROM weather_reports
    ORDER BY location, time DESC;

retrieves the most recent weather report for each location. But if we had not used ORDER BY to force descending order of time values for each location, we'd have gotten a report from an unpredictable time for each location.  

FOR UPDATE CLAUSE

The FOR UPDATE clause has this form:

FOR UPDATE [ OF table_name [, ...] ]

FOR UPDATE causes the rows retrieved by the SELECT statement to be locked as though for update. This prevents them from being modified or deleted by other transactions until the current transaction ends. That is, other transactions that attempt UPDATE, DELETE, or SELECT FOR UPDATE of these rows will be blocked until the current transaction ends. Also, if an UPDATE, DELETE, or SELECT FOR UPDATE from another transaction has already locked a selected row or rows, SELECT FOR UPDATE will wait for the other transaction to complete, and will then lock and return the updated row (or no row, if the row was deleted). For further discussion see the chapter called ``Concurrency Control'' in the documentation.

If specific tables are named in FOR UPDATE, then only rows coming from those tables are locked; any other tables used in the SELECT are simply read as usual.

FOR UPDATE cannot be used in contexts where returned rows can't be clearly identified with individual table rows; for example it can't be used with aggregation.

FOR UPDATE may appear before LIMIT for compatibility with PostgreSQL versions before 7.3. It effectively executes after LIMIT, however, and so that is the recommended place to write it.  

EXAMPLES

To join the table films with the table distributors:

SELECT f.title, f.did, d.name, f.date_prod, f.kind
    FROM distributors d, films f
    WHERE f.did = d.did

       title       | did |     name     | date_prod  |   kind
-------------------+-----+--------------+------------+----------
 The Third Man     | 101 | British Lion | 1949-12-23 | Drama
 The African Queen | 101 | British Lion | 1951-08-11 | Romantic
 ...

To sum the column len of all films and group the results by kind:

SELECT kind, sum(len) AS total FROM films GROUP BY kind;

   kind   | total
----------+-------
 Action   | 07:34
 Comedy   | 02:58
 Drama    | 14:28
 Musical  | 06:42
 Romantic | 04:38

To sum the column len of all films, group the results by kind and show those group totals that are less than 5 hours:

SELECT kind, sum(len) AS total
    FROM films
    GROUP BY kind
    HAVING sum(len) < interval '5 hours';

   kind   | total
----------+-------
 Comedy   | 02:58
 Romantic | 04:38

The following two examples are identical ways of sorting the individual results according to the contents of the second column (name):

SELECT * FROM distributors ORDER BY name;
SELECT * FROM distributors ORDER BY 2;

 did |       name
-----+------------------
 109 | 20th Century Fox
 110 | Bavaria Atelier
 101 | British Lion
 107 | Columbia
 102 | Jean Luc Godard
 113 | Luso films
 104 | Mosfilm
 103 | Paramount
 106 | Toho
 105 | United Artists
 111 | Walt Disney
 112 | Warner Bros.
 108 | Westward

This example shows how to obtain the union of the tables distributors and actors, restricting the results to those that begin with letter W in each table. Only distinct rows are wanted, so the key word ALL is omitted.

distributors:               actors:
 did |     name              id |     name
-----+--------------        ----+----------------
 108 | Westward               1 | Woody Allen
 111 | Walt Disney            2 | Warren Beatty
 112 | Warner Bros.           3 | Walter Matthau
 ...                         ...

SELECT distributors.name
    FROM distributors
    WHERE distributors.name LIKE 'W%'
UNION
SELECT actors.name
    FROM actors
    WHERE actors.name LIKE 'W%';

      name
----------------
 Walt Disney
 Walter Matthau
 Warner Bros.
 Warren Beatty
 Westward
 Woody Allen

This example shows how to use a function in the FROM clause, both with and without a column definition list.

CREATE FUNCTION distributors(int) RETURNS SETOF distributors AS '
    SELECT * FROM distributors WHERE did = $1;

SELECT * FROM distributors(111);
 did |    name
-----+-------------
 111 | Walt Disney

CREATE FUNCTION distributors_2(int) RETURNS SETOF record AS '
    SELECT * FROM distributors WHERE did = $1;

SELECT * FROM distributors_2(111) AS (f1 int, f2 text);
 f1  |     f2
-----+-------------
 111 | Walt Disney

COMPATIBILITY

Of course, the SELECT statement is compatible with the SQL standard. But there are some extensions and some missing features.  

OMITTED FROM CLAUSES

PostgreSQL allows one to omit the FROM clause. It has a straightforward use to compute the results of simple expressions:

SELECT 2+2;

 ?column?
----------
        4

Some other SQL databases cannot do this except by introducing a dummy one-row table from which to do the SELECT.

A less obvious use is to abbreviate a normal SELECT from tables:

SELECT distributors.* WHERE distributors.name = 'Westward';

 did |   name
-----+----------
 108 | Westward

This works because an implicit FROM item is added for each table that is referenced in other parts of the SELECT statement but not mentioned in FROM.

While this is a convenient shorthand, it's easy to misuse. For example, the command

SELECT distributors.* FROM distributors d;

is probably a mistake; most likely the user meant

SELECT d.* FROM distributors d;

rather than the unconstrained join

SELECT distributors.* FROM distributors d, distributors distributors;

that he will actually get. To help detect this sort of mistake, PostgreSQL will warn if the implicit-FROM feature is used in a SELECT statement that also contains an explicit FROM clause. Also, it is possible to disable the implicit-FROM feature by setting the ADD_MISSING_FROM parameter to false.  

THE AS KEY WORD

In the SQL standard, the optional key word AS is just noise and can be omitted without affecting the meaning. The PostgreSQL parser requires this key word when renaming output columns because the type extensibility features lead to parsing ambiguities without it. AS is optional in FROM items, however.  

NAMESPACE AVAILABLE TO GROUP BY AND ORDER BY

In the SQL92 standard, an ORDER BY clause may only use result column names or numbers, while a GROUP BY clause may only use expressions based on input column names. PostgreSQL extends each of these clauses to allow the other choice as well (but it uses the standard's interpretation if there is ambiguity). PostgreSQL also allows both clauses to specify arbitrary expressions. Note that names appearing in an expression will always be taken as input-column names, not as result-column names.

SQL99 uses a slightly different definition which is not upward compatible with SQL92. In most cases, however, PostgreSQL will interpret an ORDER BY or GROUP BY expression the same way SQL99 does.  

NONSTANDARD CLAUSES

The clauses DISTINCT ON, LIMIT, and OFFSET are not defined in the SQL standard.

責任編輯:韓亞珊 來源: CMPP.net
相關推薦

2011-08-24 17:46:32

SELECT INTO中文man

2011-08-24 16:48:36

man中文man

2011-08-15 10:21:09

man中文man

2011-08-11 16:11:49

at中文man

2011-08-25 10:21:56

man.conf中文man

2011-08-11 15:39:39

apm中文man

2011-08-11 17:10:55

cat中文man

2011-08-11 17:35:07

chgrp中文man

2011-08-11 17:53:06

chown中文man

2011-08-11 17:59:24

chsh中文man

2011-08-11 18:07:57

cksum中文man

2011-08-11 18:19:32

col中文man

2011-08-11 18:58:08

date中文man

2011-08-12 09:17:57

deallocvt中文man

2011-08-12 09:23:11

diff中文man

2011-08-12 09:23:16

dig中文man

2011-08-12 10:15:13

dumpkeys中文man

2011-08-12 10:41:00

file中文man

2011-08-12 11:15:27

gzip中文man

2011-08-12 13:26:56

groff中文man
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 欧美一区免费 | 亚洲色图综合 | 国产亚洲网站 | 精品国产18久久久久久二百 | 国产精品久久久久久久久久久免费看 | 一级视频在线免费观看 | 国产一区二区三区四 | 免费观看一区二区三区毛片 | 欧美男人亚洲天堂 | 中文字幕在线精品 | 久久男人天堂 | 在线婷婷 | 伊人久久精品一区二区三区 | 午夜网站视频 | 九九国产在线观看 | 毛片一级片| 亚洲毛片在线观看 | 中文字幕成人在线 | 亚洲a网 | 久久国产视频播放 | 久久久综合 | 国产亚洲精品久久情网 | 精品国产乱码久久久久久1区2区 | tube国产| 日韩一区二区在线观看视频 | 日本黄色大片免费 | 国产婷婷色一区二区三区 | 天天干天天操天天看 | 午夜国产羞羞视频免费网站 | 日韩a| 亚洲第一区国产精品 | 美女网站视频免费黄 | 一级黄a视频 | 亚洲图片视频一区 | 日韩手机在线视频 | 亚洲精品久久久久久下一站 | 亚洲精品久久久久久国产精华液 | 91网在线观看 | 亚洲精品大片 | 日韩人体在线 | 亚洲国产二区 |