📅  最后修改于: 2020-11-28 14:12:26             🧑  作者: Mango
UPDATE查询用于更新或修改表中的现有记录。我们可以将WHERE子句与UPDATE查询一起使用来更新选定的行,否则所有行都会受到影响。
以下是UPDATE查询的基本语法。
UPDATE tableName [ [ AS ] newTableAlias ] SET
{ { columnName = { DEFAULT | expression } } [,...] } |
{ ( columnName [,...] ) = ( select ) }
[ WHERE expression ] [ ORDER BY order [,...] ] [ LIMIT expression ]
在此UPDATE语法中,我们可以使用AND或OR子句组合多个条件。
考虑具有以下记录的CUSTOMER表。
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
如果要获取客户表以及给定的数据,请执行以下查询。
CREATE TABLE CUSTOMER (id number, name varchar(20), age number, address varchar(20),
salary number);
INSERT into CUSTOMER values (1, 'Ramesh', 32, 'Ahmedabad', 2000);
INSERT into CUSTOMER values (2, 'Khilan', 25, 'Delhi', 1500);
INSERT into CUSTOMER values (3, 'kaushik', 23, 'Kota', 2000);
INSERT into CUSTOMER values (4, 'Chaitali', 25, 'Mumbai', 6500);
INSERT into CUSTOMER values (5, 'Hardik', 27, 'Bhopal', 8500);
INSERT into CUSTOMER values (6, 'Komal', 22, 'MP', 4500);
INSERT into CUSTOMER values (7, 'Muffy', 24, 'Indore', 10000);
以下命令是一个示例,它将为ID为6的客户更新ADDRESS-
UPDATE CUSTOMERS SET ADDRESS = 'Pune' WHERE ID = 6;
现在,CUSTOMERS表将具有以下记录。我们可以通过执行以下查询来检查客户表记录。
SELECT * FROM CUSTOMERS;
上面的查询产生以下结果。
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | Pune | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
要修改CUSTOMERS表中的所有ADDRESS和SALARY列值,我们不需要使用WHERE子句。 UPDATE查询将如下所示-
UPDATE CUSTOMERS SET ADDRESS = 'Pune', SALARY = 1000.00;
现在,CUSTOMERS表将具有以下记录。我们可以通过执行以下查询来检查客户表记录。
SELECT * FROM CUSTOMERS;
上面的查询产生以下结果-
+----+----------+-----+---------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+---------+
| 1 | Ramesh | 32 | Pune | 1000.00 |
| 2 | Khilan | 25 | Pune | 1000.00 |
| 3 | kaushik | 23 | Pune | 1000.00 |
| 4 | Chaitali | 25 | Pune | 1000.00 |
| 5 | Hardik | 27 | Pune | 1000.00 |
| 6 | Komal | 22 | Pune | 1000.00 |
| 7 | Muffy | 24 | Pune | 1000.00 |
+----+----------+-----+---------+---------+