📜  PostgreSQL-更新查询

📅  最后修改于: 2020-11-26 06:22:02             🧑  作者: Mango


PostgreSQL UPDATE查询用于修改表中的现有记录。您可以将WHERE子句与UPDATE查询一起使用来更新选定的行。否则,将更新所有行。

句法

带WHERE子句的UPDATE查询的基本语法如下-

UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];

您可以使用AND或OR运算符组合N个条件。

考虑表COMPANY ,其记录如下:

testdb# select * from COMPANY;
 id | name  | age | address   | salary
----+-------+-----+-----------+--------
  1 | Paul  |  32 | California|  20000
  2 | Allen |  25 | Texas     |  15000
  3 | Teddy |  23 | Norway    |  20000
  4 | Mark  |  25 | Rich-Mond |  65000
  5 | David |  27 | Texas     |  85000
  6 | Kim   |  22 | South-Hall|  45000
  7 | James |  24 | Houston   |  10000
(7 rows)

以下是一个示例,它将为ID为6的客户更新ADDRESS-

testdb=# UPDATE COMPANY SET SALARY = 15000 WHERE ID = 3;

现在,COMPANY表将具有以下记录-

id | name  | age | address    | salary
----+-------+-----+------------+--------
  1 | Paul  |  32 | California |  20000
  2 | Allen |  25 | Texas      |  15000
  4 | Mark  |  25 | Rich-Mond  |  65000
  5 | David |  27 | Texas      |  85000
  6 | Kim   |  22 | South-Hall |  45000
  7 | James |  24 | Houston    |  10000
  3 | Teddy |  23 | Norway     |  15000
(7 rows)

如果要修改COMPANY表中的所有ADDRESS和SALARY列值,则无需使用WHERE子句,而UPDATE查询将如下所示-

testdb=# UPDATE COMPANY SET ADDRESS = 'Texas', SALARY=20000;

现在,COMPANY表将具有以下记录-

id | name  | age | address | salary
----+-------+-----+---------+--------
  1 | Paul  |  32 | Texas   |  20000
  2 | Allen |  25 | Texas   |  20000
  4 | Mark  |  25 | Texas   |  20000
  5 | David |  27 | Texas   |  20000
  6 | Kim   |  22 | Texas   |  20000
  7 | James |  24 | Texas   |  20000
  3 | Teddy |  23 | Texas   |  20000
(7 rows)