MySQL - 更新视图



MySQL 的UPDATE语句用于各种数据库对象,以更新其中的现有数据。这是一个 DML(数据操纵语言)命令。

在使用 UPDATE 语句时,我们需要小心,因为它可能会修改对象中的所有记录,如果没有事先选择的话。为了避免丢失或重新插入正确的数据,我们使用子句来过滤需要更新的记录。这样,我们可以有选择地更新一行或多行。

MySQL UPDATE 视图语句

在 MySQL 中,视图是一个数据库对象,可以包含来自现有表中的行(全部或选定)。它可以从一个或多个表创建,这取决于提供的 SQL 查询以创建视图。

没有直接的语句来更新 MySQL 视图。我们使用 UPDATE 语句修改视图中的全部或选择性记录。结果也会反映在原始表中。

语法

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

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

注意:我们可以使用 AND 或 OR 运算符组合 N 个条件。

示例

首先,让我们使用以下查询创建一个名为 CUSTOMERS 的表:

CREATE TABLE CUSTOMERS(
   ID int NOT NULL,
   NAME varchar(20) NOT NULL,
   AGE int NOT NULL,
   ADDRESS varchar(25),
   SALARY decimal(18, 2),
   PRIMARY KEY (ID)
);

现在,我们使用 INSERT 语句将一些记录插入此表,如下所示:

INSERT INTO CUSTOMERS VALUES 
(1, 'Ramesh', '32', 'Ahmedabad', 2000),
(2, 'Khilan', '25', 'Delhi', 1500),
(3, 'Kaushik', '23', 'Kota', 2500),
(4, 'Chaitali', '26', 'Mumbai', 6500),
(5, 'Hardik','27', 'Bhopal', 8500),
(6, 'Komal', '22', 'MP', 9000),
(7, 'Muffy', '24', 'Indore', 5500);

创建视图:

以下查询根据上面创建的表创建视图:

CREATE VIEW CUSTOMERS_VIEW AS SELECT * FROM CUSTOMERS;

使用以下查询,我们可以验证视图的内容:

SELECT * FROM CUSTOMERS_VIEW;

视图将显示如下:

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 Hyderabad 4500.00
7 Muffy 24 Indore 10000.00

更新此视图:

现在,通过我们创建的视图,我们尝试使用以下查询将 Ramesh 的年龄更新为 35,在原始 CUSTOMERS 表中:

UPDATE CUSTOMERS_VIEW SET AGE = 35 WHERE name = 'Ramesh';

这最终将更新基础表 CUSTOMERS,并且相同的更改将反映在视图本身中。

验证

使用 SELECT 查询,我们可以检索包含以下记录的实际 CUSTOMERS 表:

ID NAME AGE ADDRESS SALARY
1 Ramesh 35 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 Hyderabad 4500.00
7 Muffy 24 Indore 10000.00

更新多行和多列

在 MySQL 中,我们可以使用 UPDATE 语句更新表的多个行和列。要更新多行,请在 WHERE 子句中指定条件,以便只有所需的行满足该条件。

要更新多列,请将新值设置为需要更新的所有列。在这种情况下,使用 WHERE 子句将缩小表的记录范围,而不使用该子句将更改这些列中的所有值。

语法

以下是更新多行和多列的语法:

UPDATE table_name
SET column_name1 = new_value, column_name2 = new_value...
WHERE condition(s)

示例

在以下查询中,我们尝试修改 CUSTOMERS 表中 WHERE ID = 3 的 NAME 和 AGE 列值

UPDATE CUSTOMERS_VIEW 
SET NAME = 'Kaushik', AGE = 24
WHERE ID = 3;

验证

使用 SELECT 查询,我们可以检索包含以下记录的 CUSTOMERS 表:

ID NAME AGE ADDRESS SALARY
1 Ramesh 35 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 Kaushik 24 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 Hyderabad 4500.00
7 Muffy 24 Indore 10000.00

示例

如果我们想修改 CUSTOMERS 表中 AGE 列的所有记录,我们可以使用以下查询:

UPDATE CUSTOMERS_VIEW SET AGE = 24;

输出

此查询产生以下输出:

Query OK, 5 rows affected (0.01 sec)
Rows matched: 7  Changed: 5  Warnings: 0

验证

使用 SELECT 查询,我们显示包含以下记录的 CUSTOMERS 表:

ID NAME AGE ADDRESS SALARY
1 Ramesh 24 Ahmedabad 2000.00
2 Khilan 24 Delhi 1500.00
3 Kaushik 24 Kota 2000.00
4 Chaitali 24 Mumbai 6500.00
5 Hardik 24 Bhopal 8500.00
6 Komal 24 Hyderabad 4500.00
7 Muffy 24 Indore 10000.00

使用客户端程序更新视图

我们已经学习了如何使用 SQL UPDATE 查询更新视图。除此之外,我们还可以使用其他客户端程序对视图执行更新操作。

语法

要通过 PHP 程序更新 MySQL 数据库中的视图,我们需要使用名为query()mysqli函数执行 UPDATE 或 ALTER 语句,如下所示:

$sql = "ALTER VIEW first_view AS SELECT tutorial_id, tutorial_title, tutorial_author FROM clone_table WHERE tutorial_id = 101";
$mysqli->query($sql);

要通过 JavaScript 程序更新 MySQL 数据库中的视图,我们需要使用mysql2库的query()函数执行 UPDATE 或 ALTER 语句,如下所示:

sql = "UPDATE CUSTOMERS_VIEW SET AGE = 35 WHERE name = 'Ramesh'";
con.query(sql);  

要通过 Java 程序更新 MySQL 数据库中的视图,我们需要使用 **JDBC** 函数 **executeUpdate()** 执行 UPDATE 或 ALTER 语句,如下所示:

String sql = "ALTER VIEW first_view AS select tutorial_id, tutorial_title, tutorial_author from tutorials_tbl where tutorial_id = 1";
st.execute(sql);

要通过 Python 程序更新 MySQL 数据库中的视图,我们需要使用 **MySQL Connector/Python** 的 **execute()** 函数执行 UPDATE 或 ALTER 语句,如下所示:

update_view_query = "UPDATE tutorial_view SET tutorial_title = 'New Title' WHERE tutorial_id = 2"
cursorObj.execute(update_view_query)

示例

以下是程序:

$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$dbname = 'TUTORIALS';
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);

if ($mysqli->connect_errno) {
    printf("Connect failed: %s
", $mysqli->connect_error); exit(); } // printf('Connected successfully.
'); // A view can be updated by using the CREATE OR REPLACE; $sql = "ALTER VIEW first_view AS SELECT tutorial_id, tutorial_title, tutorial_author FROM clone_table WHERE tutorial_id = 101"; if ($mysqli->query($sql)) { printf("View updated successfully!.
"); } if ($mysqli->errno) { printf("View could not be updated!.
", $mysqli->error); } $mysqli->close();

输出

获得的输出如下所示:

View updated successfully!. 
var mysql = require('mysql2');
var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "Nr5a0204@123"
});

  //Connecting to MySQL
  con.connect(function (err) {
  if (err) throw err;
  console.log("Connected!");
  console.log("--------------------------");

  sql = "create database TUTORIALS"
  con.query(sql);

  sql = "USE TUTORIALS"
  con.query(sql);

  sql = "CREATE TABLE CUSTOMERS(ID int NOT NULL, NAME varchar(20) NOT NULL, AGE int NOT NULL, ADDRESS varchar(25), SALARY decimal(18, 2), PRIMARY KEY (ID) );"
  con.query(sql);

  sql = "INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (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 );"
  con.query(sql);

  sql = "CREATE VIEW CUSTOMERS_VIEW AS SELECT * FROM CUSTOMERS;"
  con.query(sql);

  //Displaying contents of the view
  sql = "SELECT * from CUSTOMERS_VIEW;"
  con.query(sql, function(err, result){
    if (err) throw err
    console.log("**CUSTOMERS_VIEW View:**");
    console.log(result);
    console.log("--------------------------");
  });

  sql = "UPDATE CUSTOMERS_VIEW SET AGE = 35 WHERE name = 'Ramesh'";
  con.query(sql);

  //retrieving the base table
  sql = "SELECT * FROM CUSTOMERS;"
  con.query(sql, function(err, result){
    if (err) throw err
    console.log("**Base Table(CUSTOMERS):**");
    console.log(result);
  });
});  

输出

产生的输出如下所示:

Connected!
--------------------------
**CUSTOMERS_VIEW View:**
[
  {ID: 1, NAME: 'Ramesh', AGE: 32, ADDRESS: 'Ahmedabad', SALARY: '2000.00'},
  {ID: 2, NAME: 'Khilan', AGE: 25, ADDRESS: 'Delhi', SALARY: '1500.00'},
  {ID: 3, NAME: 'kaushik', AGE: 23, ADDRESS: 'Kota', SALARY: '2000.00'},
  {ID: 4, NAME: 'Chaitali', AGE: 25, ADDRESS: 'Mumbai', SALARY: '6500.00'},
  {ID: 5, NAME: 'Hardik', AGE: 27, ADDRESS: 'Bhopal', SALARY: '8500.00'},
  {ID: 6, NAME: 'Komal', AGE: 22, ADDRESS: 'MP', SALARY: '4500.00' },
  {ID: 7, NAME: 'Muffy', AGE: 24, ADDRESS: 'Indore', SALARY: '10000.00'}
]
--------------------------
**Base Table(CUSTOMERS):**
[
  {ID: 1, NAME: 'Ramesh', AGE: 35, ADDRESS: 'Ahmedabad', SALARY: '2000.00'},
  {ID: 2, NAME: 'Khilan', AGE: 25, ADDRESS: 'Delhi', SALARY: '1500.00'},
  {ID: 3, NAME: 'kaushik', AGE: 23, ADDRESS: 'Kota', SALARY: '2000.00'},
  {ID: 4, NAME: 'Chaitali', AGE: 25, ADDRESS: 'Mumbai', SALARY: '6500.00'},
  {ID: 5, NAME: 'Hardik', AGE: 27, ADDRESS: 'Bhopal', SALARY: '8500.00'},
  {ID: 6, NAME: 'Komal', AGE: 22, ADDRESS: 'MP', SALARY: '4500.00' },
  {ID: 7, NAME: 'Muffy', AGE: 24, ADDRESS: 'Indore', SALARY: '10000.00'}
]
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class UpdateView {
   public static void main(String[] args) {
      String url = "jdbc:mysql://127.0.0.1:3306/TUTORIALS";
      String username = "root";
      String password = "password";
      try {
         Class.forName("com.mysql.cj.jdbc.Driver");
         Connection connection = DriverManager.getConnection(url, username, password);
         Statement statement = connection.createStatement();
         System.out.println("Connected successfully...!");

         //Update Created View.....
         String sql = "ALTER VIEW first_view AS select tutorial_id, tutorial_title, tutorial_author from tutorials_tbl where tutorial_id = 1";
         statement.execute(sql);
         System.out.println("Created view updated Successfully...!");
         ResultSet resultSet = statement.executeQuery("SELECT * FROM first_view");
         while (resultSet.next()) {
            System.out.print(resultSet.getInt(1)+" "+ resultSet.getString(2)+ " "+ resultSet.getString(3));
            System.out.println();
         }
         connection.close();
      } catch (Exception e) {
         System.out.println(e);
      }
   }
}

输出

获得的输出如下所示:

Connected successfully...!
Created view updated Successfully...!
1 Learn PHP John Paul
import mysql.connector
#establishing the connection
connection = mysql.connector.connect(
    host='localhost',
    user='root',
    password='password',
    database='tut'
)
cursorObj = connection.cursor()
update_view_query = """
UPDATE tutorial_view
SET tutorial_title = 'New Title'
WHERE tutorial_id = 2
"""
cursorObj.execute(update_view_query)
connection.commit()
print("View updated successfully.")
cursorObj.close()
connection.close()               

输出

以下是上述代码的输出:

View updated successfully.
广告