Home Database Mysql Tutorial MySQL的replace into详解

MySQL的replace into详解

Jun 07, 2016 pm 05:51 PM
replace

本教程主要拿了两篇文章来介绍关于mysql的replace into语句的用法,有需要的朋友可以参考一下。

REPLACE的运行与INSERT很相像。只有一点除外,如果表中的一个旧记录与一个用于PRIMARY KEY或一个UNIQUE索引的新记录具有相同的值,则在新记录被插入之前,旧记录被删除。

注意,除非表有一个PRIMARY KEY或UNIQUE索引,否则,使用一个REPLACE语句没有意义。该语句会与INSERT相同,因为没有索引被用于确定是否新行复制了其它的行。

所有列的值均取自在REPLACE语句中被指定的值。所有缺失的列被设置为各自的默认值,这和INSERT一样。您不能从当前行中引用值,也不能在新行中使用值。如果您使用一个例如“SET col_name = col_name + 1”的赋值,则对位于右侧的列名称的引用会被作为DEFAULT(col_name)处理。因此,该赋值相当于SET col_name = DEFAULT(col_name) + 1。

为了能够使用REPLACE,您必须同时拥有表的INSERT和DELETE权限。

REPLACE语句会返回一个数,来指示受影响的行的数目。该数是被删除和被插入的行数的和。如果对于一个单行REPLACE该数为1,则一行被插入,同时没有行被删除。如果该数大于1,则在新行被插入前,有一个或多个旧行被删除。如果表包含多个唯一索引,并且新行复制了在不同的唯一索引中的不同旧行的值,则有可能是一个单一行替换了多个旧行。

受影响的行数可以容易地确定是否REPLACE只添加了一行,或者是否REPLACE也替换了其它行:检查该数是否为1(添加)或更大(替换)。

如果您正在使用C API,则可以使用_affected_rows()函数获得受影响的行数。

目前,您不能在一个子查询中,向一个表中更换,同时从同一个表中选择。

以下是所用算法的更详细的说明(该算法也用于LOAD DATA…REPLACE):

1. 尝试把新行插入到表中

2. 当因为对于主键或唯一关键字出现重复关键字错误而造成插入失败时:

a. 从表中删除含有重复关键字值的冲突行

b. 再次尝试把新行插入到表中

今天喉咙疼死我了,闪人睡觉去.

使用格式:

 代码如下 复制代码

REPLACE [LOW_PRIORITY | DELAYED]
[INTO] tbl_name [(col_name,...)]
VALUES ({expr | DEFAULT},…),(…),…
或:

REPLACE [LOW_PRIORITY | DELAYED]
[INTO] tbl_name
SET col_name={expr | DEFAULT}, …
或:

REPLACE [LOW_PRIORITY | DELAYED]
[INTO] tbl_name [(col_name,...)]
SELECT …


一。 REPLACE INTO table_name ( `col_A`, `col_B`) VALUES ( `col A data`, `col B data`) ;

Replaces items in a row. This action is dependant on the "id" because when doing a REPLACE, you must include the PRIMARY (unique) column. Since we established the "id" column as our PRIMARY key (when establishing the table), MySQL needs this info so it knows which row we are talking about. If we didn't include the "id" coumn, MySQL will have no idea which row we are trying to replace.

In this example, we are replacing row #2

 代码如下 复制代码

$sql = "REPLACE INTO music (id,artist,album) VALUES ('2','The Beatles','Let It Be')";mysql_query($sql);
id artist album title track year
1 the beatles Abbey Road   
2 The Beatles Let It Be   
3  Abbey Road 3 test   
Records: 3

 

Here, we haven't defined the "id" column. Hence, MySQL doesn't know which row to replace, so it just adds a new row.

So as we can see, the REPLACE feature acts very similar to INSERT. We can use this to our advantage!

Again, REPLACE behaves much like INSERT except that:
- if the PRIMARY ("unique column") is supplied, the existing row will be updated
- if the PRIMARY ("unique column") is not provided, a new row will be added.

 代码如下 复制代码

$sql = "REPLACE INTO music (artist,album) VALUES ('The Beatles','The Magical Mystery Tour')";mysql_query($sql);
id artist album title track year
1 the beatles Abbey Road   
2 The Beatles Let It Be   
3  Abbey Road 3 test   
4 The Beatles The Magical Mystery Tour   
Records: 4

NOTE: You may get errors when trying this kind of REPLACE, because usually the "unique column" can not be null (or empty). Some people like to set up the database where the "unique column" is automatically incremented by MySQL. This is kind of confusing and can lead to a headache. So just remember to include the "unique column" when using the REPLACE statement, or you'll get duplicate rows... OR use the UPDATE statement.

二。 Mysql replace into 与 insert into on duplicate key update 的区别这两种方式的作用是如果中存在记录就更新,否则就插入新记录,但是在使用上也是有一点区别的。 总结如下: 1. 如果表中不存在主键记录,replace和insert*update都与insert是一样的特点。 2. 如果表中存在主键记录,replace相当于执行delete 和 insert两条操作,而insert*update的相当于执行if exist do update else do insert操作。因此,如果replace填充的字段不全,则会导致未被更新的字段都会修改为默认值,并且如果有自增id的话,自增id会变化为最新的值(这样如果是以自增id为标志的话可能导致记录丢失);而insert*update只是更新部分字段,对于未被更新的字段不会变化(不会强制修改为默认值)。

三。unique键的情况

如果存在unique键(无论是某个字段或者是组合字段), replace into执行的效果是:如果unique键对应的内容已经存在,那么更新主键;如果unique键对应的内容不存在,则插入一条记录。

 

Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain InnoDB Full-Text Search capabilities. Explain InnoDB Full-Text Search capabilities. Apr 02, 2025 pm 06:09 PM

InnoDB's full-text search capabilities are very powerful, which can significantly improve database query efficiency and ability to process large amounts of text data. 1) InnoDB implements full-text search through inverted indexing, supporting basic and advanced search queries. 2) Use MATCH and AGAINST keywords to search, support Boolean mode and phrase search. 3) Optimization methods include using word segmentation technology, periodic rebuilding of indexes and adjusting cache size to improve performance and accuracy.

How do you alter a table in MySQL using the ALTER TABLE statement? How do you alter a table in MySQL using the ALTER TABLE statement? Mar 19, 2025 pm 03:51 PM

The article discusses using MySQL's ALTER TABLE statement to modify tables, including adding/dropping columns, renaming tables/columns, and changing column data types.

When might a full table scan be faster than using an index in MySQL? When might a full table scan be faster than using an index in MySQL? Apr 09, 2025 am 12:05 AM

Full table scanning may be faster in MySQL than using indexes. Specific cases include: 1) the data volume is small; 2) when the query returns a large amount of data; 3) when the index column is not highly selective; 4) when the complex query. By analyzing query plans, optimizing indexes, avoiding over-index and regularly maintaining tables, you can make the best choices in practical applications.

Can I install mysql on Windows 7 Can I install mysql on Windows 7 Apr 08, 2025 pm 03:21 PM

Yes, MySQL can be installed on Windows 7, and although Microsoft has stopped supporting Windows 7, MySQL is still compatible with it. However, the following points should be noted during the installation process: Download the MySQL installer for Windows. Select the appropriate version of MySQL (community or enterprise). Select the appropriate installation directory and character set during the installation process. Set the root user password and keep it properly. Connect to the database for testing. Note the compatibility and security issues on Windows 7, and it is recommended to upgrade to a supported operating system.

Difference between clustered index and non-clustered index (secondary index) in InnoDB. Difference between clustered index and non-clustered index (secondary index) in InnoDB. Apr 02, 2025 pm 06:25 PM

The difference between clustered index and non-clustered index is: 1. Clustered index stores data rows in the index structure, which is suitable for querying by primary key and range. 2. The non-clustered index stores index key values ​​and pointers to data rows, and is suitable for non-primary key column queries.

What are some popular MySQL GUI tools (e.g., MySQL Workbench, phpMyAdmin)? What are some popular MySQL GUI tools (e.g., MySQL Workbench, phpMyAdmin)? Mar 21, 2025 pm 06:28 PM

Article discusses popular MySQL GUI tools like MySQL Workbench and phpMyAdmin, comparing their features and suitability for beginners and advanced users.[159 characters]

How do you handle large datasets in MySQL? How do you handle large datasets in MySQL? Mar 21, 2025 pm 12:15 PM

Article discusses strategies for handling large datasets in MySQL, including partitioning, sharding, indexing, and query optimization.

How do you drop a table in MySQL using the DROP TABLE statement? How do you drop a table in MySQL using the DROP TABLE statement? Mar 19, 2025 pm 03:52 PM

The article discusses dropping tables in MySQL using the DROP TABLE statement, emphasizing precautions and risks. It highlights that the action is irreversible without backups, detailing recovery methods and potential production environment hazards.

See all articles