PostgreSQL UPDATE查询

PostgreSQL的UPDATE查询被用来修改现有的表中的记录。可以使用UPDATE查询的WHERE子句更新选定行,否则会被更新的所有行。

语法:

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

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

可以结合使用AND或OR运算的N多条件。

实例:

考虑表公司有如下记录:

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地址:

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

现在公司表有以下记录:

 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)

如果想修改公司表中所有的地址和薪酬列值,则不需要使用WHERE子句和UPDATE查询将如下:

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

现在公司表将有以下记录:

 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)

    点赞