gooderp18绿色标准版
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

281 行
20KB

  1. <?xml version="1.0" encoding="UTF-8" standalone="no"?>
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>UPDATE</title><link rel="stylesheet" type="text/css" href="stylesheet.css" /><link rev="made" href="pgsql-docs@lists.postgresql.org" /><meta name="generator" content="DocBook XSL Stylesheets V1.79.1" /><link rel="prev" href="sql-unlisten.html" title="UNLISTEN" /><link rel="next" href="sql-vacuum.html" title="VACUUM" /></head><body><div xmlns="http://www.w3.org/TR/xhtml1/transitional" class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="5" align="center">UPDATE</th></tr><tr><td width="10%" align="left"><a accesskey="p" href="sql-unlisten.html" title="UNLISTEN">Prev</a> </td><td width="10%" align="left"><a accesskey="u" href="sql-commands.html" title="SQL Commands">Up</a></td><th width="60%" align="center">SQL Commands</th><td width="10%" align="right"><a accesskey="h" href="index.html" title="PostgreSQL 12.4 Documentation">Home</a></td><td width="10%" align="right"> <a accesskey="n" href="sql-vacuum.html" title="VACUUM">Next</a></td></tr></table><hr></hr></div><div class="refentry" id="SQL-UPDATE"><div class="titlepage"></div><a id="id-1.9.3.182.1" class="indexterm"></a><div class="refnamediv"><h2><span class="refentrytitle">UPDATE</span></h2><p>UPDATE — update rows of a table</p></div><div class="refsynopsisdiv"><h2>Synopsis</h2><pre class="synopsis">
  3. [ WITH [ RECURSIVE ] <em class="replaceable"><code>with_query</code></em> [, ...] ]
  4. UPDATE [ ONLY ] <em class="replaceable"><code>table_name</code></em> [ * ] [ [ AS ] <em class="replaceable"><code>alias</code></em> ]
  5. SET { <em class="replaceable"><code>column_name</code></em> = { <em class="replaceable"><code>expression</code></em> | DEFAULT } |
  6. ( <em class="replaceable"><code>column_name</code></em> [, ...] ) = [ ROW ] ( { <em class="replaceable"><code>expression</code></em> | DEFAULT } [, ...] ) |
  7. ( <em class="replaceable"><code>column_name</code></em> [, ...] ) = ( <em class="replaceable"><code>sub-SELECT</code></em> )
  8. } [, ...]
  9. [ FROM <em class="replaceable"><code>from_item</code></em> [, ...] ]
  10. [ WHERE <em class="replaceable"><code>condition</code></em> | WHERE CURRENT OF <em class="replaceable"><code>cursor_name</code></em> ]
  11. [ RETURNING * | <em class="replaceable"><code>output_expression</code></em> [ [ AS ] <em class="replaceable"><code>output_name</code></em> ] [, ...] ]
  12. </pre></div><div class="refsect1" id="id-1.9.3.182.5"><h2>Description</h2><p>
  13. <code class="command">UPDATE</code> changes the values of the specified
  14. columns in all rows that satisfy the condition. Only the columns to
  15. be modified need be mentioned in the <code class="literal">SET</code> clause;
  16. columns not explicitly modified retain their previous values.
  17. </p><p>
  18. There are two ways to modify a table using information contained in
  19. other tables in the database: using sub-selects, or specifying
  20. additional tables in the <code class="literal">FROM</code> clause. Which
  21. technique is more appropriate depends on the specific
  22. circumstances.
  23. </p><p>
  24. The optional <code class="literal">RETURNING</code> clause causes <code class="command">UPDATE</code>
  25. to compute and return value(s) based on each row actually updated.
  26. Any expression using the table's columns, and/or columns of other
  27. tables mentioned in <code class="literal">FROM</code>, can be computed.
  28. The new (post-update) values of the table's columns are used.
  29. The syntax of the <code class="literal">RETURNING</code> list is identical to that of the
  30. output list of <code class="command">SELECT</code>.
  31. </p><p>
  32. You must have the <code class="literal">UPDATE</code> privilege on the table,
  33. or at least on the column(s) that are listed to be updated.
  34. You must also have the <code class="literal">SELECT</code>
  35. privilege on any column whose values are read in the
  36. <em class="replaceable"><code>expressions</code></em> or
  37. <em class="replaceable"><code>condition</code></em>.
  38. </p></div><div class="refsect1" id="id-1.9.3.182.6"><h2>Parameters</h2><div class="variablelist"><dl class="variablelist"><dt><span class="term"><em class="replaceable"><code>with_query</code></em></span></dt><dd><p>
  39. The <code class="literal">WITH</code> clause allows you to specify one or more
  40. subqueries that can be referenced by name in the <code class="command">UPDATE</code>
  41. query. See <a class="xref" href="queries-with.html" title="7.8. WITH Queries (Common Table Expressions)">Section 7.8</a> and <a class="xref" href="sql-select.html" title="SELECT"><span class="refentrytitle">SELECT</span></a>
  42. for details.
  43. </p></dd><dt><span class="term"><em class="replaceable"><code>table_name</code></em></span></dt><dd><p>
  44. The name (optionally schema-qualified) of the table to update.
  45. If <code class="literal">ONLY</code> is specified before the table name, matching rows
  46. are updated in the named table only. If <code class="literal">ONLY</code> is not
  47. specified, matching rows are also updated in any tables inheriting from
  48. the named table. Optionally, <code class="literal">*</code> can be specified after the
  49. table name to explicitly indicate that descendant tables are included.
  50. </p></dd><dt><span class="term"><em class="replaceable"><code>alias</code></em></span></dt><dd><p>
  51. A substitute name for the target table. When an alias is
  52. provided, it completely hides the actual name of the table. For
  53. example, given <code class="literal">UPDATE foo AS f</code>, the remainder of the
  54. <code class="command">UPDATE</code> statement must refer to this table as
  55. <code class="literal">f</code> not <code class="literal">foo</code>.
  56. </p></dd><dt><span class="term"><em class="replaceable"><code>column_name</code></em></span></dt><dd><p>
  57. The name of a column in the table named by <em class="replaceable"><code>table_name</code></em>.
  58. The column name can be qualified with a subfield name or array
  59. subscript, if needed. Do not include the table's name in the
  60. specification of a target column — for example,
  61. <code class="literal">UPDATE table_name SET table_name.col = 1</code> is invalid.
  62. </p></dd><dt><span class="term"><em class="replaceable"><code>expression</code></em></span></dt><dd><p>
  63. An expression to assign to the column. The expression can use the
  64. old values of this and other columns in the table.
  65. </p></dd><dt><span class="term"><code class="literal">DEFAULT</code></span></dt><dd><p>
  66. Set the column to its default value (which will be NULL if no
  67. specific default expression has been assigned to it).
  68. </p></dd><dt><span class="term"><em class="replaceable"><code>sub-SELECT</code></em></span></dt><dd><p>
  69. A <code class="literal">SELECT</code> sub-query that produces as many output columns
  70. as are listed in the parenthesized column list preceding it. The
  71. sub-query must yield no more than one row when executed. If it
  72. yields one row, its column values are assigned to the target columns;
  73. if it yields no rows, NULL values are assigned to the target columns.
  74. The sub-query can refer to old values of the current row of the table
  75. being updated.
  76. </p></dd><dt><span class="term"><em class="replaceable"><code>from_item</code></em></span></dt><dd><p>
  77. A table expression allowing columns from other tables to appear in
  78. the <code class="literal">WHERE</code> condition and update expressions. This
  79. uses the same syntax as the <a class="xref" href="sql-select.html#SQL-FROM" title="FROM Clause"><code class="literal">FROM</code> Clause</a> of a <code class="command">SELECT</code> statement;
  80. for example, an alias for the table name can be specified. Do not
  81. repeat the target table as a <em class="replaceable"><code>from_item</code></em>
  82. unless you intend a self-join (in which case it must appear with
  83. an alias in the <em class="replaceable"><code>from_item</code></em>).
  84. </p></dd><dt><span class="term"><em class="replaceable"><code>condition</code></em></span></dt><dd><p>
  85. An expression that returns a value of type <code class="type">boolean</code>.
  86. Only rows for which this expression returns <code class="literal">true</code>
  87. will be updated.
  88. </p></dd><dt><span class="term"><em class="replaceable"><code>cursor_name</code></em></span></dt><dd><p>
  89. The name of the cursor to use in a <code class="literal">WHERE CURRENT OF</code>
  90. condition. The row to be updated is the one most recently fetched
  91. from this cursor. The cursor must be a non-grouping
  92. query on the <code class="command">UPDATE</code>'s target table.
  93. Note that <code class="literal">WHERE CURRENT OF</code> cannot be
  94. specified together with a Boolean condition. See
  95. <a class="xref" href="sql-declare.html" title="DECLARE"><span class="refentrytitle">DECLARE</span></a>
  96. for more information about using cursors with
  97. <code class="literal">WHERE CURRENT OF</code>.
  98. </p></dd><dt><span class="term"><em class="replaceable"><code>output_expression</code></em></span></dt><dd><p>
  99. An expression to be computed and returned by the <code class="command">UPDATE</code>
  100. command after each row is updated. The expression can use any
  101. column names of the table named by <em class="replaceable"><code>table_name</code></em>
  102. or table(s) listed in <code class="literal">FROM</code>.
  103. Write <code class="literal">*</code> to return all columns.
  104. </p></dd><dt><span class="term"><em class="replaceable"><code>output_name</code></em></span></dt><dd><p>
  105. A name to use for a returned column.
  106. </p></dd></dl></div></div><div class="refsect1" id="id-1.9.3.182.7"><h2>Outputs</h2><p>
  107. On successful completion, an <code class="command">UPDATE</code> command returns a command
  108. tag of the form
  109. </p><pre class="screen">
  110. UPDATE <em class="replaceable"><code>count</code></em>
  111. </pre><p>
  112. The <em class="replaceable"><code>count</code></em> is the number
  113. of rows updated, including matched rows whose values did not change.
  114. Note that the number may be less than the number of rows that matched
  115. the <em class="replaceable"><code>condition</code></em> when
  116. updates were suppressed by a <code class="literal">BEFORE UPDATE</code> trigger. If
  117. <em class="replaceable"><code>count</code></em> is 0, no rows were
  118. updated by the query (this is not considered an error).
  119. </p><p>
  120. If the <code class="command">UPDATE</code> command contains a <code class="literal">RETURNING</code>
  121. clause, the result will be similar to that of a <code class="command">SELECT</code>
  122. statement containing the columns and values defined in the
  123. <code class="literal">RETURNING</code> list, computed over the row(s) updated by the
  124. command.
  125. </p></div><div class="refsect1" id="id-1.9.3.182.8"><h2>Notes</h2><p>
  126. When a <code class="literal">FROM</code> clause is present, what essentially happens
  127. is that the target table is joined to the tables mentioned in the
  128. <em class="replaceable"><code>from_item</code></em> list, and each output row of the join
  129. represents an update operation for the target table. When using
  130. <code class="literal">FROM</code> you should ensure that the join
  131. produces at most one output row for each row to be modified. In
  132. other words, a target row shouldn't join to more than one row from
  133. the other table(s). If it does, then only one of the join rows
  134. will be used to update the target row, but which one will be used
  135. is not readily predictable.
  136. </p><p>
  137. Because of this indeterminacy, referencing other tables only within
  138. sub-selects is safer, though often harder to read and slower than
  139. using a join.
  140. </p><p>
  141. In the case of a partitioned table, updating a row might cause it to no
  142. longer satisfy the partition constraint of the containing partition. In that
  143. case, if there is some other partition in the partition tree for which this
  144. row satisfies its partition constraint, then the row is moved to that
  145. partition. If there is no such partition, an error will occur. Behind the
  146. scenes, the row movement is actually a <code class="command">DELETE</code> and
  147. <code class="command">INSERT</code> operation.
  148. </p><p>
  149. There is a possibility that a concurrent <code class="command">UPDATE</code> or
  150. <code class="command">DELETE</code> on the row being moved will get a serialization
  151. failure error. Suppose session 1 is performing an <code class="command">UPDATE</code>
  152. on a partition key, and meanwhile a concurrent session 2 for which this
  153. row is visible performs an <code class="command">UPDATE</code> or
  154. <code class="command">DELETE</code> operation on this row. In such case,
  155. session 2's <code class="command">UPDATE</code> or <code class="command">DELETE</code> will
  156. detect the row movement and raise a serialization failure error (which
  157. always returns with an SQLSTATE code '40001'). Applications may wish to
  158. retry the transaction if this occurs. In the usual case where the table
  159. is not partitioned, or where there is no row movement, session 2 would
  160. have identified the newly updated row and carried out the
  161. <code class="command">UPDATE</code>/<code class="command">DELETE</code> on this new row
  162. version.
  163. </p><p>
  164. Note that while rows can be moved from local partitions to a foreign-table
  165. partition (provided the foreign data wrapper supports tuple routing), they
  166. cannot be moved from a foreign-table partition to another partition.
  167. </p></div><div class="refsect1" id="id-1.9.3.182.9"><h2>Examples</h2><p>
  168. Change the word <code class="literal">Drama</code> to <code class="literal">Dramatic</code> in the
  169. column <code class="structfield">kind</code> of the table <code class="structname">films</code>:
  170. </p><pre class="programlisting">
  171. UPDATE films SET kind = 'Dramatic' WHERE kind = 'Drama';
  172. </pre><p>
  173. </p><p>
  174. Adjust temperature entries and reset precipitation to its default
  175. value in one row of the table <code class="structname">weather</code>:
  176. </p><pre class="programlisting">
  177. UPDATE weather SET temp_lo = temp_lo+1, temp_hi = temp_lo+15, prcp = DEFAULT
  178. WHERE city = 'San Francisco' AND date = '2003-07-03';
  179. </pre><p>
  180. </p><p>
  181. Perform the same operation and return the updated entries:
  182. </p><pre class="programlisting">
  183. UPDATE weather SET temp_lo = temp_lo+1, temp_hi = temp_lo+15, prcp = DEFAULT
  184. WHERE city = 'San Francisco' AND date = '2003-07-03'
  185. RETURNING temp_lo, temp_hi, prcp;
  186. </pre><p>
  187. </p><p>
  188. Use the alternative column-list syntax to do the same update:
  189. </p><pre class="programlisting">
  190. UPDATE weather SET (temp_lo, temp_hi, prcp) = (temp_lo+1, temp_lo+15, DEFAULT)
  191. WHERE city = 'San Francisco' AND date = '2003-07-03';
  192. </pre><p>
  193. </p><p>
  194. Increment the sales count of the salesperson who manages the
  195. account for Acme Corporation, using the <code class="literal">FROM</code>
  196. clause syntax:
  197. </p><pre class="programlisting">
  198. UPDATE employees SET sales_count = sales_count + 1 FROM accounts
  199. WHERE accounts.name = 'Acme Corporation'
  200. AND employees.id = accounts.sales_person;
  201. </pre><p>
  202. </p><p>
  203. Perform the same operation, using a sub-select in the
  204. <code class="literal">WHERE</code> clause:
  205. </p><pre class="programlisting">
  206. UPDATE employees SET sales_count = sales_count + 1 WHERE id =
  207. (SELECT sales_person FROM accounts WHERE name = 'Acme Corporation');
  208. </pre><p>
  209. </p><p>
  210. Update contact names in an accounts table to match the currently assigned
  211. salesmen:
  212. </p><pre class="programlisting">
  213. UPDATE accounts SET (contact_first_name, contact_last_name) =
  214. (SELECT first_name, last_name FROM salesmen
  215. WHERE salesmen.id = accounts.sales_id);
  216. </pre><p>
  217. A similar result could be accomplished with a join:
  218. </p><pre class="programlisting">
  219. UPDATE accounts SET contact_first_name = first_name,
  220. contact_last_name = last_name
  221. FROM salesmen WHERE salesmen.id = accounts.sales_id;
  222. </pre><p>
  223. However, the second query may give unexpected results
  224. if <code class="structname">salesmen</code>.<code class="structfield">id</code> is not a unique key, whereas
  225. the first query is guaranteed to raise an error if there are multiple
  226. <code class="structfield">id</code> matches. Also, if there is no match for a particular
  227. <code class="structname">accounts</code>.<code class="structfield">sales_id</code> entry, the first query
  228. will set the corresponding name fields to NULL, whereas the second query
  229. will not update that row at all.
  230. </p><p>
  231. Update statistics in a summary table to match the current data:
  232. </p><pre class="programlisting">
  233. UPDATE summary s SET (sum_x, sum_y, avg_x, avg_y) =
  234. (SELECT sum(x), sum(y), avg(x), avg(y) FROM data d
  235. WHERE d.group_id = s.group_id);
  236. </pre><p>
  237. </p><p>
  238. Attempt to insert a new stock item along with the quantity of stock. If
  239. the item already exists, instead update the stock count of the existing
  240. item. To do this without failing the entire transaction, use savepoints:
  241. </p><pre class="programlisting">
  242. BEGIN;
  243. -- other operations
  244. SAVEPOINT sp1;
  245. INSERT INTO wines VALUES('Chateau Lafite 2003', '24');
  246. -- Assume the above fails because of a unique key violation,
  247. -- so now we issue these commands:
  248. ROLLBACK TO sp1;
  249. UPDATE wines SET stock = stock + 24 WHERE winename = 'Chateau Lafite 2003';
  250. -- continue with other operations, and eventually
  251. COMMIT;
  252. </pre><p>
  253. </p><p>
  254. Change the <code class="structfield">kind</code> column of the table
  255. <code class="structname">films</code> in the row on which the cursor
  256. <code class="literal">c_films</code> is currently positioned:
  257. </p><pre class="programlisting">
  258. UPDATE films SET kind = 'Dramatic' WHERE CURRENT OF c_films;
  259. </pre></div><div class="refsect1" id="id-1.9.3.182.10"><h2>Compatibility</h2><p>
  260. This command conforms to the <acronym class="acronym">SQL</acronym> standard, except
  261. that the <code class="literal">FROM</code> and <code class="literal">RETURNING</code> clauses
  262. are <span class="productname">PostgreSQL</span> extensions, as is the ability
  263. to use <code class="literal">WITH</code> with <code class="command">UPDATE</code>.
  264. </p><p>
  265. Some other database systems offer a <code class="literal">FROM</code> option in which
  266. the target table is supposed to be listed again within <code class="literal">FROM</code>.
  267. That is not how <span class="productname">PostgreSQL</span> interprets
  268. <code class="literal">FROM</code>. Be careful when porting applications that use this
  269. extension.
  270. </p><p>
  271. According to the standard, the source value for a parenthesized sub-list of
  272. target column names can be any row-valued expression yielding the correct
  273. number of columns. <span class="productname">PostgreSQL</span> only allows the
  274. source value to be a <a class="link" href="sql-expressions.html#SQL-SYNTAX-ROW-CONSTRUCTORS" title="4.2.13. Row Constructors">row
  275. constructor</a> or a sub-<code class="literal">SELECT</code>. An individual column's
  276. updated value can be specified as <code class="literal">DEFAULT</code> in the
  277. row-constructor case, but not inside a sub-<code class="literal">SELECT</code>.
  278. </p></div></div><div class="navfooter"><hr /><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="sql-unlisten.html">Prev</a> </td><td width="20%" align="center"><a accesskey="u" href="sql-commands.html">Up</a></td><td width="40%" align="right"> <a accesskey="n" href="sql-vacuum.html">Next</a></td></tr><tr><td width="40%" align="left" valign="top">UNLISTEN </td><td width="20%" align="center"><a accesskey="h" href="index.html">Home</a></td><td width="40%" align="right" valign="top"> VACUUM</td></tr></table></div></body></html>
上海开阖软件有限公司 沪ICP备12045867号-1