Table of Contents
How to skip copy errors
How to execute SQL that does not copy from a library
How to manually fix master-slave data differences
How to ignore certain SQL statements in replication
Home Database SQL MySQL Replication Strategies with SQL

MySQL Replication Strategies with SQL

Jul 29, 2025 am 03:04 AM

Common SQL operation strategies in MySQL replication include: 1. Skip errors: STOP SLAVE; SET GLOBAL SQL_SLAVE_SKIP_COUNTER = 1; START SLAVE; Suitable for temporary processing of non-fatal errors; 2. Do not copy SQL from the library: Use SET SQL_LOG_BIN=0 to turn off binary logging, and then turn it on after performing the operation, requiring SUPER permission; 3. Manually repair data differences: After closing the copy thread, missing data is manually inserted from the library. It is recommended to combine the pt-table-checksum tool to verify consistency; 4. Ignore specific SQL replication: use replicate-wild-ignore-table parameters or CHANGE REPLICATION FILTER dynamically sets filtering replication tables. The above operations should be carefully evaluated to avoid causing data inconsistencies or other problems.

MySQL Replication Strategies with SQL

MySQL replication (Replication) is a common data synchronization mechanism, which is often used in master-slave architecture to achieve data redundancy, read-write separation and high availability. If you are using MySQL Replication, you may encounter situations where you need to execute certain SQL statements during the replication process, such as tuning configuration, repairing data, or performing batch operations. At this time, it is particularly important to master some commonly used SQL strategies.

MySQL Replication Strategies with SQL

The following are some common and practical strategies for using MySQL Replication in actual operations.


How to skip copy errors

During the replication process, some non-fatal errors are often encountered, such as primary key conflicts caused by inconsistency in master-slave data or statement execution failure. If you do not want these errors to interrupt replication, you can use SQL to skip the error.

MySQL Replication Strategies with SQL

Common practices are:

  • Stop copying threads from the library:

    MySQL Replication Strategies with SQL
     STOP SLAVE;
  • Skip an error event:

     SET GLOBAL SQL_SLAVE_SKIP_COUNTER = 1;
  • Restart the replication:

     START SLAVE;

⚠️ Note: This method is suitable for temporary treatment and is not recommended for long-term use. Skip errors may lead to further inconsistencies in the data. It is recommended to operate on the premise of confirming that the risks are controllable.


How to execute SQL that does not copy from a library

Sometimes you want to execute some SQL statements on the slave library, but you don't want these statements to be copied to other nodes. For example, you might want to add a temporary index to the slave library, but you don't want to affect the main library structure.

You can use SET SQL_LOG_BIN = 0; to temporarily close the binary logging of the current session:

 SET SQL_LOG_BIN = 0;
CREATE INDEX idx_temp ON your_table(temp_column);
SET SQL_LOG_BIN = 1;

In this way, this CREATE INDEX statement will not be recorded in the binary log and will not be copied to other slave libraries.

⚠️ Note: SUPER permission is required to perform this operation. In addition, this operation only takes effect in the current session and will not affect other connections.


How to manually fix master-slave data differences

If you find that the data is inconsistent between the master and slave, sometimes you need to manually execute SQL statements to synchronize the data. For example, the main library has a data record ID 100, while the slave library does not.

You can manually insert this record from the library:

 INSERT INTO your_table (id, col1, col2) VALUES (100, 'value1', 'value2');

However, there are risks in direct operation from the inventory. It is recommended:

  • Make sure the insert statement also exists in the main library, otherwise an error may occur next time you copy it
  • Close the copy thread before insertion, and then turn on after insertion
  • Automatically detect and fix data differences using pt-table-checksum and pt-table-sync tools

How to ignore certain SQL statements in replication

If you want certain SQL statements not to participate in replication, you can set replication filtering rules in the main library, such as through replicate-wild-ignore-table parameter configuration.

For example, add:

 replicate-wild-ignore-table=your_db.temp_%
replicate-wild-ignore-table=mysql.%

In this way, all tables matching your_db.temp_* and tables under the mysql database will not be copied.

If you don't want to modify the configuration file, you can also use SQL to dynamically set it:

 CHANGE REPLICATION FILTER REPLICATE_IGNORE_TABLE = (your_db.temp_table);

This method is suitable for temporarily ignoring the copying of certain tables.


Basically that's it. There are many usage scenarios in MySQL Replication, and the key is to understand the scope of action and potential impact of each statement. Although operations such as skipping errors, closing copy and executing SQL, and manually repairing data, are not complicated, but they are easily more serious problems due to misoperation, so it is best to confirm clearly before execution.

The above is the detailed content of MySQL Replication Strategies with SQL. For more information, please follow other related articles on the PHP Chinese website!

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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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

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)

Hot Topics

PHP Tutorial
1596
276
How do you calculate the difference between two dates in SQL? How do you calculate the difference between two dates in SQL? Aug 02, 2025 pm 01:29 PM

To calculate the difference between two dates, you need to select the corresponding function according to the database type: 1. Use DATEDIFF() to calculate the day difference in MySQL, or specify the units such as HOUR and MINUTE in TIMESTAMPDIFF(); 2. Use DATEDIFF(date_part, start_date, end_date) in SQLServer and specify the units; 3. Use direct subtraction in PostgreSQL to obtain the day difference, or use EXTRACT(DAYFROMAGE(...)) to obtain more accurate intervals; 4. Use julianday() function to subtract the day difference in SQLite; always pay attention to the date order

What are the BLOB and CLOB data types in SQL? What are the BLOB and CLOB data types in SQL? Aug 07, 2025 pm 04:22 PM

BLOBstoresbinarydatalikeimages,audio,orPDFsasrawbyteswithoutcharacterencoding,whileCLOBstoreslargetextsuchasarticlesorJSONusingcharacterencodinglikeUTF-8andsupportsstringoperations;2.Bothcanhandleuptogigabytesofdatadependingonthedatabase,butperforman

SQL Cube and Rollup for Multi-Dimensional Aggregation SQL Cube and Rollup for Multi-Dimensional Aggregation Jul 29, 2025 am 12:28 AM

CUBE is used to generate aggregation of all dimension combinations, suitable for cross-analysis; ROLLUP is gradually summarized at hierarchical levels, suitable for data with hierarchical relationships. CUBE generates a total of 8 combinations according to Region, Product, and Quarter, while ROLLUP generates a summary of year, month, day and other levels according to Year, Month, and Day. CUBE is suitable for viewing all cross-dimensional results, ROLLUP is suitable for displaying hierarchies. Note that CUBE may cause the result set to explode, and ROLLUP depends on the field order. The summary row can be identified through the GROUPING() function, and the total row is named with COALESCE to improve readability.

How does the EXISTS operator compare to the IN operator in SQL? How does the EXISTS operator compare to the IN operator in SQL? Aug 05, 2025 pm 01:08 PM

UseEXISTSforexistencechecks,especiallywithlargeorcorrelatedsubqueriesandwhenNULLvaluesarepresent,asitstopsatthefirstmatchandhandlesNULLssafely;useINformembershipchecksagainstsmall,known,ornon-nullvaluesetswherereadabilitymattersandperformanceisnotcri

How do you grant and revoke permissions in SQL? How do you grant and revoke permissions in SQL? Aug 04, 2025 am 09:19 AM

GRANTandREVOKEstatementsareusedtomanageuserpermissionsinSQL.1.GRANTprovidesprivilegeslikeSELECT,INSERT,UPDATE,DELETE,ALTER,EXECUTE,orALLPRIVILEGESondatabaseobjectstousersorroles.2.SyntaxforgrantingisGRANTprivilege_typeONobject_nameTOuser_or_role,allo

Optimizing SQL ORDER BY for Query Performance Optimizing SQL ORDER BY for Query Performance Aug 04, 2025 am 11:19 AM

To optimize the performance of ORDERBY in SQL, you must first understand its execution mechanism and make rational use of index and query structure. When the sorting field has no index, the database will trigger "filesort", consuming a lot of resources; therefore, direct sorting of large tables should be avoided and the amount of sorted data should be reduced through WHERE conditions. Secondly, establishing a matching index for sorting fields can greatly speed up queries, such as creating reverse order indexes in MySQL 8.0 to improve efficiency. In addition, deep paging (such as LIMIT1000, 10) should be used instead with index-based cursor paging (such as WHEREid>12345) to skip invalid scans. Finally, combining caching, asynchronous aggregation and other means can also further optimize the sorting performance in large data set scenarios.

How to get the first and last day of the year in SQL? How to get the first and last day of the year in SQL? Aug 11, 2025 pm 05:42 PM

ThefirstdayoftheyearisobtainedbyconstructingortruncatingtoJanuary1stofthegivenyear,andthelastdayisDecember31stofthesameyear,withmethodsvaryingbydatabasesystem;2.Fordynamiccurrentyeardates,MySQLusesDATE_FORMATorMAKEDATE,PostgreSQLusesDATE_TRUNCorDATE_

How to find the sum of a column in SQL? How to find the sum of a column in SQL? Aug 08, 2025 pm 05:54 PM

TofindthesumofacolumninSQL,usetheSUM()function,whichreturnsthetotalofallnumericvaluesinaspecifiedcolumnwhileignoringNULLs;1.Usebasicsyntax:SELECTSUM(column_name)ASaliasFROMtable_name;2.Ensurethecolumnhasnumericdatatoavoiderrors;3.ApplyWHEREtofilterro

See all articles