select.7

来自「PostgreSQL 8.2中增加了很多企业用户所需要的功能和性能上的提高,其开」· 7 代码 · 共 886 行 · 第 1/2 页

7
886
字号
.\\" auto-generated by docbook2man-spec $Revision: 1.1.1.1 $.TH "SELECT" "" "2008-01-03" "SQL - Language Statements" "SQL Commands".SH NAMESELECT \- retrieve rows from a table or view.SH SYNOPSIS.sp.nfSELECT [ ALL | DISTINCT [ ON ( \fIexpression\fR [, ...] ) ] ]    * | \fIexpression\fR [ AS \fIoutput_name\fR ] [, ...]    [ FROM \fIfrom_item\fR [, ...] ]    [ WHERE \fIcondition\fR ]    [ GROUP BY \fIexpression\fR [, ...] ]    [ HAVING \fIcondition\fR [, ...] ]    [ { UNION | INTERSECT | EXCEPT } [ ALL ] \fIselect\fR ]    [ ORDER BY \fIexpression\fR [ ASC | DESC | USING \fIoperator\fR ] [, ...] ]    [ LIMIT { \fIcount\fR | ALL } ]    [ OFFSET \fIstart\fR ]    [ FOR { UPDATE | SHARE } [ OF \fItable_name\fR [, ...] ] [ NOWAIT ] [...] ]where \fIfrom_item\fR can be one of:    [ ONLY ] \fItable_name\fR [ * ] [ [ AS ] \fIalias\fR [ ( \fIcolumn_alias\fR [, ...] ) ] ]    ( \fIselect\fR ) [ AS ] \fIalias\fR [ ( \fIcolumn_alias\fR [, ...] ) ]    \fIfunction_name\fR ( [ \fIargument\fR [, ...] ] ) [ AS ] \fIalias\fR [ ( \fIcolumn_alias\fR [, ...] | \fIcolumn_definition\fR [, ...] ) ]    \fIfunction_name\fR ( [ \fIargument\fR [, ...] ] ) AS ( \fIcolumn_definition\fR [, ...] )    \fIfrom_item\fR [ NATURAL ] \fIjoin_type\fR \fIfrom_item\fR [ ON \fIjoin_condition\fR | USING ( \fIjoin_column\fR [, ...] ) ].sp.fi.SH "DESCRIPTION".PP\fBSELECT\fR retrieves rows from zero or more tables.The general processing of \fBSELECT\fR is as follows:.IP 1. All elements in the FROM list are computed.(Each element in the FROM list is a real orvirtual table.) If more than one element is specified in theFROM list, they are cross-joined together.(See FROM Clause [\fBselect\fR(7)] below.).IP 2. If the WHERE clause is specified, all rowsthat do not satisfy the condition are eliminated from theoutput. (See WHERE Clause [\fBselect\fR(7)] below.).IP 3. If the GROUP BY clause is specified, theoutput is divided into groups of rows that match on one or morevalues. If the HAVING clause is present, iteliminates groups that do not satisfy the given condition. (SeeGROUP BY Clause [\fBselect\fR(7)] andHAVING Clause [\fBselect\fR(7)] below.).IP 4. The actual output rows are computed using the\fBSELECT\fR output expressions for each selectedrow. (SeeSELECT List [\fBselect\fR(7)]below.).IP 5. Using the operators UNION,INTERSECT, and EXCEPT, theoutput of more than one \fBSELECT\fR statement canbe combined to form a single result set. TheUNION operator returns all rows that are inone or both of the result sets. TheINTERSECT operator returns all rows that arestrictly in both result sets. The EXCEPToperator returns the rows that are in the first result set butnot in the second. In all three cases, duplicate rows areeliminated unless ALL is specified. (SeeUNION Clause [\fBselect\fR(7)], INTERSECT Clause [\fBselect\fR(l)], andEXCEPT Clause [\fBselect\fR(7)] below.).IP 6. If the ORDER BY clause is specified, thereturned rows are sorted in the specified order. IfORDER BY is not given, the rows are returnedin whatever order the system finds fastest to produce. (SeeORDER BY Clause [\fBselect\fR(7)] below.).IP 7. DISTINCT eliminates duplicate rows from theresult. DISTINCT ON eliminates rows thatmatch on all the specified expressions. ALL(the default) will return all candidate rows, includingduplicates. (See DISTINCT Clause [\fBselect\fR(7)] below.).IP 8. If the LIMIT or OFFSETclause is specified, the \fBSELECT\fR statementonly returns a subset of the result rows. (See LIMIT Clause [\fBselect\fR(7)] below.).IP 9. If FOR UPDATE or FOR SHAREis specified, the\fBSELECT\fR statement locks the selected rowsagainst concurrent updates. (See FOR UPDATE/FOR SHARE Clause [\fBselect\fR(7)] below.).PP.PPYou must have SELECT privilege on a table toread its values. The use of FOR UPDATE orFOR SHARE requiresUPDATE privilege as well..SH "PARAMETERS".SS "FROM CLAUSE".PPThe FROM clause specifies one or more sourcetables for the \fBSELECT\fR. If multiple sources arespecified, the result is the Cartesian product (cross join) of allthe sources. But usually qualification conditionsare added to restrict the returned rows to a small subset of theCartesian product..PPThe FROM clause can contain the followingelements:.TP\fB\fItable_name\fB\fRThe name (optionally schema-qualified) of an existing table orview. If ONLY is specified, only that table isscanned. If ONLY is not specified, the table andall its descendant tables (if any) are scanned. *can be appended to the table name to indicate that descendanttables are to be scanned, but in the current version, this isthe default behavior. (In releases before 7.1,ONLY was the default behavior.) The defaultbehavior can be modified by changing the sql_inheritance configuration option..TP\fB\fIalias\fB\fRA substitute name for the FROM item containing thealias. An alias is used for brevity or to eliminate ambiguityfor self-joins (where the same table is scanned multipletimes). When an alias is provided, it completely hides theactual name of the table or function; for example givenFROM foo AS f, the remainder of the\fBSELECT\fR must refer to this FROMitem as f not foo. If an alias iswritten, a column alias list can also be written to providesubstitute names for one or more columns of the table..TP\fB\fIselect\fB\fRA sub-\fBSELECT\fR can appear in theFROM clause. This acts as though itsoutput were created as a temporary table for the duration ofthis single \fBSELECT\fR command. Note that thesub-\fBSELECT\fR must be surrounded byparentheses, and an alias \fBmust\fR beprovided for it. AVALUES [\fBvalues\fR(7)] commandcan also be used here..TP\fB\fIfunction_name\fB\fRFunction calls can appear in the FROMclause. (This is especially useful for functions that returnresult sets, but any function can be used.) This acts asthough its output were created as a temporary table for theduration of this single \fBSELECT\fR command. Analias may also be used. If an alias is written, a column aliaslist can also be written to provide substitute names for oneor more attributes of the function's composite return type. Ifthe function has been defined as returning the \fBrecord\fRdata type, then an alias or the key word AS mustbe present, followed by a column definition list in the form( \fIcolumn_name\fR \fIdata_type\fR [, ... ]). The column definition list must match the actualnumber and types of columns returned by the function..TP\fB\fIjoin_type\fB\fROne of.RS.TP 0.2i\(bu[ INNER ] JOIN.TP 0.2i\(buLEFT [ OUTER ] JOIN.TP 0.2i\(buRIGHT [ OUTER ] JOIN.TP 0.2i\(buFULL [ OUTER ] JOIN.TP 0.2i\(buCROSS JOIN.RE.PPFor the INNER and OUTER join types, ajoin condition must be specified, namely exactly one ofNATURAL, ON \fIjoin_condition\fR, orUSING (\fIjoin_column\fR [, ...]).See below for the meaning. For CROSS JOIN,none of these clauses may appear.A JOIN clause combines twoFROM items. Use parentheses if necessary todetermine the order of nesting. In the absence of parentheses,JOINs nest left-to-right. In any caseJOIN binds more tightly than the commasseparating FROM items.CROSS JOIN and INNER JOINproduce a simple Cartesian product, the same result as you get fromlisting the two items at the top level of FROM,but restricted by the join condition (if any).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 theydo nothing you couldn't do with plain FROM andWHERE.LEFT OUTER JOIN returns all rows in the qualifiedCartesian product (i.e., all combined rows that pass its joincondition), plus one copy of each row in the left-hand tablefor which there was no right-hand row that passed the joincondition. This left-hand row is extended to the full widthof the joined table by inserting null values for theright-hand columns. Note that only the JOINclause's own condition is considered while deciding which rowshave matches. Outer conditions are applied afterwards.Conversely, RIGHT OUTER JOIN returns all thejoined rows, plus one row for each unmatched right-hand row(extended with nulls on the left). This is just a notationalconvenience, since you could convert it to a LEFTOUTER JOIN by switching the left and right inputs.FULL OUTER JOIN returns all the joined rows, plusone row for each unmatched left-hand row (extended with nullson the right), plus one row for each unmatched right-hand row(extended with nulls on the left)..TP\fBON \fIjoin_condition\fB\fR\fIjoin_condition\fR isan expression resulting in a value of type\fBboolean\fR (similar to a WHEREclause) that specifies which rows in a join are considered tomatch..TP\fBUSING (\fIjoin_column\fB [, ...])\fRA clause of the form USING ( a, b, ... ) isshorthand for ON left_table.a = right_table.a ANDleft_table.b = right_table.b .... Also,USING implies that only one of each pair ofequivalent columns will be included in the join output, notboth..TP\fBNATURAL\fRNATURAL is shorthand for aUSING list that mentions all columns in the twotables that have the same names..PP.SS "WHERE CLAUSE".PPThe optional WHERE clause has the general form.sp.nfWHERE \fIcondition\fR.sp.fiwhere \fIcondition\fR isany expression that evaluates to a result of type\fBboolean\fR. Any row that does not satisfy thiscondition will be eliminated from the output. A row satisfies thecondition if it returns true when the actual row values aresubstituted for any variable references..SS "GROUP BY CLAUSE".PPThe optional GROUP BY clause has the general form.sp.nfGROUP BY \fIexpression\fR [, ...].sp.fi.PPGROUP BY will condense into a single row allselected rows that share the same values for the groupedexpressions. \fIexpression\fR can be an input columnname, or the name or ordinal number of an output column(\fBSELECT\fR list item), or an arbitraryexpression formed from input-column values. In case of ambiguity,a GROUP BY name will be interpreted as aninput-column name rather than an output column name..PPAggregate functions, if any are used, are computed across all rowsmaking up each group, producing a separate value for each group(whereas without GROUP BY, an aggregateproduces a single value computed across all the selected rows).When GROUP BY is present, it is not valid forthe \fBSELECT\fR list expressions to refer toungrouped columns except within aggregate functions, since therewould be more than one possible value to return for an ungroupedcolumn..SS "HAVING CLAUSE".PPThe optional HAVING clause has the general form.sp.nfHAVING \fIcondition\fR.sp.fiwhere \fIcondition\fR isthe same as specified for the WHERE clause..PPHAVING eliminates group rows that do notsatisfy the condition. HAVING is differentfrom WHERE: WHERE filtersindividual rows before the application of GROUPBY, while HAVING filters group rowscreated by GROUP BY. Each column referenced in\fIcondition\fR mustunambiguously reference a grouping column, unless the referenceappears within an aggregate function..PPThe presence of HAVING turns a query into a groupedquery even if there is no GROUP BY clause. This is thesame as what happens when the query contains aggregate functions butno GROUP BY clause. All the selected rows are considered toform a single group, and the \fBSELECT\fR list andHAVING clause can only reference table columns fromwithin aggregate functions. Such a query will emit a single row if theHAVING condition is true, zero rows if it is not true..SS "SELECT LIST".PPThe \fBSELECT\fR list (between the key wordsSELECT and FROM) specifies expressionsthat form the output rows of the \fBSELECT\fRstatement. The expressions can (and usually do) refer to columnscomputed in the FROM clause. Using the clauseAS \fIoutput_name\fR, anothername can be specified for an output column. This name isprimarily used to label the column for display. It can also beused to refer to the column's value in ORDER BY andGROUP BY clauses, but not in the WHERE orHAVING clauses; there you must write out theexpression instead..PPInstead of an expression, * can be written inthe output list as a shorthand for all the columns of the selectedrows. Also, one can write \fItable_name\fR.* as ashorthand for the columns coming from just that table..SS "UNION CLAUSE".PPThe UNION clause has this general form:.sp.nf\fIselect_statement\fR UNION [ ALL ] \fIselect_statement\fR.sp.fi\fIselect_statement\fR isany \fBSELECT\fR statement without an ORDERBY, LIMIT, FOR UPDATE, orFOR SHARE clause.(ORDER BY and LIMIT can be attached to asubexpression if it is enclosed in parentheses. Withoutparentheses, these clauses will be taken to apply to the result ofthe UNION, not to its right-hand inputexpression.).PPThe UNION operator computes the set union ofthe rows returned by the involved \fBSELECT\fRstatements. A row is in the set union of two result sets if itappears in at least one of the result sets. The two\fBSELECT\fR statements that represent the directoperands of the UNION must produce the samenumber of columns, and corresponding columns must be of compatibledata types..PPThe result of UNION does not contain any duplicaterows unless the ALL option is specified.ALL prevents elimination of duplicates. (Therefore,UNION ALL is usually significantly quicker thanUNION; use ALL when you can.).PPMultiple UNION operators in the same\fBSELECT\fR statement are evaluated left to right,unless otherwise indicated by parentheses..PPCurrently, FOR UPDATE and FOR SHARE may not bespecified either for a UNION result or for any input of aUNION..SS "INTERSECT CLAUSE".PPThe INTERSECT clause has this general form:.sp.nf\fIselect_statement\fR INTERSECT [ ALL ] \fIselect_statement\fR.sp.fi\fIselect_statement\fR isany \fBSELECT\fR statement without an ORDERBY, LIMIT, FOR UPDATE, orFOR SHARE clause..PPThe INTERSECT operator computes the setintersection of the rows returned by the involved\fBSELECT\fR statements. A row is in theintersection of two result sets if it appears in both result sets..PPThe result of INTERSECT does not contain anyduplicate rows unless the ALL option is specified.With ALL, a row that has \fIm\fR duplicates in theleft table and \fIn\fR duplicates in the right table will appearmin(\fIm\fR,\fIn\fR) times in the result set..PPMultiple INTERSECT operators in the same\fBSELECT\fR statement are evaluated left to right,unless parentheses dictate otherwise.INTERSECT binds more tightly thanUNION. That is, A UNION B INTERSECTC will be read as A UNION (B INTERSECTC)..PPCurrently, FOR UPDATE and FOR SHARE may not bespecified either for an INTERSECT result or for any input ofan INTERSECT..SS "EXCEPT CLAUSE".PPThe EXCEPT clause has this general form:.sp.nf\fIselect_statement\fR EXCEPT [ ALL ] \fIselect_statement\fR.sp.fi\fIselect_statement\fR isany \fBSELECT\fR statement without an ORDERBY, LIMIT, FOR UPDATE, orFOR SHARE clause..PPThe EXCEPT operator computes the set of rowsthat are in the result of the left \fBSELECT\fRstatement but not in the result of the right one..PPThe result of EXCEPT does not contain anyduplicate rows unless the ALL option is specified.With ALL, a row that has \fIm\fR duplicates in theleft table and \fIn\fR duplicates in the right table will appearmax(\fIm\fR-\fIn\fR,0) times in the result set..PPMultiple EXCEPT operators in the same\fBSELECT\fR statement are evaluated left to right,unless parentheses dictate otherwise. EXCEPT binds atthe same level as UNION..PPCurrently, FOR UPDATE and FOR SHARE may not bespecified either for an EXCEPT result or for any input ofan EXCEPT..SS "ORDER BY CLAUSE".PPThe optional ORDER BY clause has this general form:

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?