search
HomeDatabaseMysql Tutorial执行一次SQL查询,UPDATE多行记录_MySQL

bitsCN.com

执行一次SQL查询,UPDATE多行记录

 

通常情况下,我们会使用以下SQL语句来更新字段值:

1

UPDATE mytable SET myfield='value' WHERE other_field='other_value';

     但是,如果你想更新多行数据,并且每行记录的各字段值都是各不一样,你会怎么办呢?举个例子,我的博客有三个分类目录(免费资源、教程指南、橱窗展示),这些分类目录的信息存储在数据库表categories中,并且设置了显示顺序字段 display_order,每个分类占一行记录。如果我想重新编排这些分类目录的顺序,例如改成(教程指南、橱窗展示、免费资源),这时就需要更新categories表相应行的display_order字段,这就涉及到更新多行记录的问题了,刚开始你可能会想到使用循环执行多条UPDATE语句的方式,就像以下的php程序示例:

 

foreach ($display_order as $id => $ordinal) {

    $sql="UPDATE categories SET display_order = $ordinal WHERE id = $id";

    mysql_query($sql);

}

     这种方法并没有什么任何错误,并且代码简单易懂,但是在循环语句中执行了不止一次SQL查询,在做系统优化的时候,我们总是想尽可能的减少数据库查询的次数,以减少资源占用,同时可以提高系统速度。幸运的是,还有更好的解决方案,只不过SQL语句稍微复杂点,但是只需执行一次查询即可,语法如下:

 

UPDATE mytable

    SET myfield = CASE other_field

        WHEN 1 THEN 'value'

        WHEN 2 THEN 'value'

        WHEN 3 THEN 'value'

    END

WHERE id IN (1,2,3)

     回到我们刚才的分类目录的例子,我们可以使用以下SQL语句:

 

UPDATE categories

    SET display_order = CASE id

        WHEN 1 THEN 3

        WHEN 2 THEN 1

        WHEN 3 THEN 2

    END

WHERE id IN (1,2,3)

     这样的SQL语句是很容易理解的,也就是用到了很多编程语言都有的关键字 CASE,根据id字段值来进行不同分支的当型判断,进而更新display_order字段值。例如原来id=1的记录的display_order改成了3,id=2的记录的display_order改成了1,只需执行一次查询即可更新多行记录。在通常情况,WHERE子句是可有可无的,添加该WHERE子句的意义与其他用到WHERE子句的普通SQL是一样的。
 

     如果你需要更新一行记录的多个字段,可以用以下SQL语句:

 

UPDATE categories

    SET display_order = CASE id

        WHEN 1 THEN 3

        WHEN 2 THEN 4

        WHEN 3 THEN 5

    END,

    title = CASE id

        WHEN 1 THEN 'New Title 1'

        WHEN 2 THEN 'New Title 2'

        WHEN 3 THEN 'New Title 3'

    END

WHERE id IN (1,2,3)

     以上方案大大减少了数据库的查询操作次数,大大节约了系统资源,但是该怎样与我们的编程语言结合起来呢?我们还是用刚才分类目录的例子,以下是php的程序示例:

 

$display_order = array(

    1 => 4,

    2 => 1,

    3 => 2,

    4 => 3,

    5 => 9,

    6 => 5,

    7 => 8,

    8 => 9

);

 

$ids = implode(',', array_keys($display_order));

$sql = "UPDATE categories SET display_order = CASE id ";

foreach ($display_order as $id => $ordinal) {

    $sql .= sprintf("WHEN %d THEN %d ", $id, $ordinal);  // 拼接SQL语句

}

$sql .= "END WHERE id IN ($ids)";

echo $sql;

mysql_query($sql);

     在这个例子中总共更新了8行数据,但是只执行了一次数据库查询,相比于循环执行8次UPDATE语句,以上例子所节约的时间可以说是微不足道的。但是想想,当你需要更新10,0000或者更多行记录时,你会发现这其中的好处!唯一要注意的问题是SQL语句的长度,需要考虑程序运行环境所支持的字符串长度,我目前获得的数据:SQL语句长度达到1,000,960在php中仍然可以顺利执行,我查询了php文档并没有发现明确规定字符串最大长度。

bitsCN.com
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Explain the InnoDB Buffer Pool and its importance for performance.Explain the InnoDB Buffer Pool and its importance for performance.Apr 19, 2025 am 12:24 AM

InnoDBBufferPool reduces disk I/O by caching data and indexing pages, improving database performance. Its working principle includes: 1. Data reading: Read data from BufferPool; 2. Data writing: After modifying the data, write to BufferPool and refresh it to disk regularly; 3. Cache management: Use the LRU algorithm to manage cache pages; 4. Reading mechanism: Load adjacent data pages in advance. By sizing the BufferPool and using multiple instances, database performance can be optimized.

MySQL vs. Other Programming Languages: A ComparisonMySQL vs. Other Programming Languages: A ComparisonApr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

Learning MySQL: A Step-by-Step Guide for New UsersLearning MySQL: A Step-by-Step Guide for New UsersApr 19, 2025 am 12:19 AM

MySQL is worth learning because it is a powerful open source database management system suitable for data storage, management and analysis. 1) MySQL is a relational database that uses SQL to operate data and is suitable for structured data management. 2) The SQL language is the key to interacting with MySQL and supports CRUD operations. 3) The working principle of MySQL includes client/server architecture, storage engine and query optimizer. 4) Basic usage includes creating databases and tables, and advanced usage involves joining tables using JOIN. 5) Common errors include syntax errors and permission issues, and debugging skills include checking syntax and using EXPLAIN commands. 6) Performance optimization involves the use of indexes, optimization of SQL statements and regular maintenance of databases.

MySQL: Essential Skills for Beginners to MasterMySQL: Essential Skills for Beginners to MasterApr 18, 2025 am 12:24 AM

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL: Structured Data and Relational DatabasesMySQL: Structured Data and Relational DatabasesApr 18, 2025 am 12:22 AM

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL: Key Features and Capabilities ExplainedMySQL: Key Features and Capabilities ExplainedApr 18, 2025 am 12:17 AM

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

The Purpose of SQL: Interacting with MySQL DatabasesThe Purpose of SQL: Interacting with MySQL DatabasesApr 18, 2025 am 12:12 AM

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

MySQL for Beginners: Getting Started with Database ManagementMySQL for Beginners: Getting Started with Database ManagementApr 18, 2025 am 12:10 AM

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software