Maison base de données tutoriel mysql [转] INSERT INTO ... SELECT Performance with Innodb tables_MySQL

[转] INSERT INTO ... SELECT Performance with Innodb tables_MySQL

Jun 01, 2016 pm 01:51 PM

Author: peter
url: http://www.mysqlperformanceblog.com/2006/07/12/insert-into-select-performance-with-innodb-tables/


Everyone using Innodb tables probably got use to the fact Innodb tables perform non locking reads, meaning unless you use some modifiers such as LOCK IN SHARE MODE or FOR UPDATE, SELECT statements will not lock any rows while running.

This is generally correct, however there a notable exception - INSERT INTO table1 SELECT * FROM table2. This statement will perform locking read (shared locks) for table2 table. It also applies to similar tables with where clause and joins. It is important for tables which is being read to be Innodb - even if writes are done in MyISAM table.

So why was this done, being pretty bad for MySQL Performance and concurrency ? The reason is - replication. In MySQL before 5.1 replication is statement based which means statements replied on the master should cause the same effect as on the slave. If Innodb would not locking rows in source table other transaction could modify the row and commit before transaction which is running INSERT .. SELECT statement. This would make this transaction to be applied on the slave before INSERT... SELECT statement and possibly result in different data than on master. Locking rows in the source table while reading them protects from this effect as other transaction modifies rows before INSERT ... SELECT had chance to access it it will also be modified in the same order on the slave. If transaction tries to modify the row after it was accessed and so locked by INSERT ... SELECT, transaction will have to wait until statement is completed to make sure it will be executed on the slave in proper order. Gets pretty complicated ? Well all you need to know it had to be done fore replication to work right in MySQL before 5.1.

In MySQL 5.1 this as well as few other problems should be solved by row based replication. I'm however yet to give it real stress tests to see how well it performs :)

One more thing to keep into account - INSERT ... SELECT actually performs read in locking mode and so partially bypasses versioning and retrieves latest committed row. So even if you're operation in REPEATABLE-READ mode, this operation will be performed in READ-COMMITTED mode, potentially giving different result compared to what pure SELECT would give. This by the way applies to SELECT .. LOCK IN SHARE MODE and SELECT ... FOR UPDATE as well.

One my ask what is if I'm not using replication and have my binary log disabled ? If replication is not used you can enable innodb_locks_unsafe_for_binlog option, which will relax locks which Innodb sets on statement execution, which generally gives better concurrency. However as the name says it makes locks unsafe fore replication and point in time recovery, so use innodb_locks_unsafe_for_binlog option with caution.

Note disabling binary logs is not enough to trigger relaxed locks. You have to set innodb_locks_unsafe_for_binlog=1 as well. This is done so enabling binary log does not cause unexpected changes in locking behavior and performance problems. You also can use this option with replication sometimes, if you really know what you're doing. I would not recommend it unless it is really needed as you might not know which other locks will be relaxed in future versions and how it would affect your replication.

So what are safe workarounds if you're using replication ?

The most general one is to use: PLAIN TEXT SQL:

  1. SELECT * FROM tbl1 INFO OUTFILE '/tmp/tbl1.txt';
  2. LOAD DATA INFILE '/tmp/tbl1.txt' INTO TABLE tbl2;

instead of: PLAIN TEXT SQL:

  1. INSERT INTO tbl2 SELECT * FROM tbl1;

INSERT ... INTO OUTFILE does not have to set extra locks.

If you use this aproach make sure to delete file after it is loaded back (it has to be done outside of MySQL Server) as otherwise the script will fail second time.

If you need result to be even closer to one of INSERT ... SELECT you may execute this transaction in READ-COMMITTED isolation mode.

Other workarounds are less general purpose. For example if you're doing batch processing which is well indexed you might chop transactions and process rows by small bulks, which do not cause long enough locks to cause the problems.

To complete this article I should show how wait caused by this statement will look in SHOW INNODB STATUS:

<pre class="brush:php;toolbar:false">TRANSACTION 0 42304626, ACTIVE 14 sec, process no 29895, OS thread id 2894768 updating or deleting<br />mysql tables in use 1, locked 1<br />LOCK WAIT 3 lock struct(s), heap size 320, undo log entries 1<br />MySQL thread id 1794760, query id 6994946 localhost root Updating<br />update sample set j=0 where i=5<br />TRX HAS BEEN WAITING 14 SEC FOR THIS LOCK TO BE GRANTED:<br />RECORD LOCKS space id 0 page no 33504 n bits 328 index `j` of table `test/sample` trx id 0 42304626 lock_mode X locks rec but not gap waiting<br />Record lock, heap no 180 PHYSICAL RECORD: n_fields 2; compact format; info bits 0<br />0: len 30; hex 306338386465646233353863643936633930363962373361353736383261; asc 0c88dedb358cd96c9069b73a57682a;...(truncated); 1: len 4; hex 00000005; asc ;;<br /><br />TRANSACTION 0 42304624, ACTIVE 37 sec, process no 29895, OS thread id 4058032 fetching rows, thread declared inside InnoDB 3<br />mysql tables in use 1, locked 1<br />2539 lock struct(s), heap size 224576<br />MySQL thread id 1794751, query id 6994931 localhost root Sending data<br />insert into test select * from sample
Copier après la connexion

As you can see INSERT... SELECT has a lot of lock structs, which means it has locked a lot of rows. "fetching rows" of course means it is still going. In this case write is done to MyISAM table so we'll not see any write activity.

Other transaction which happes to be simple primary key update is waiting on sample table for this record to be unlocked.


Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn

Outils d'IA chauds

Undresser.AI Undress

Undresser.AI Undress

Application basée sur l'IA pour créer des photos de nu réalistes

AI Clothes Remover

AI Clothes Remover

Outil d'IA en ligne pour supprimer les vêtements des photos.

Undress AI Tool

Undress AI Tool

Images de déshabillage gratuites

Clothoff.io

Clothoff.io

Dissolvant de vêtements AI

AI Hentai Generator

AI Hentai Generator

Générez AI Hentai gratuitement.

Article chaud

R.E.P.O. Crystals d'énergie expliqués et ce qu'ils font (cristal jaune)
2 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Meilleurs paramètres graphiques
2 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌

Outils chauds

Bloc-notes++7.3.1

Bloc-notes++7.3.1

Éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise

SublimeText3 version chinoise

Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1

Envoyer Studio 13.0.1

Puissant environnement de développement intégré PHP

Dreamweaver CS6

Dreamweaver CS6

Outils de développement Web visuel

SublimeText3 version Mac

SublimeText3 version Mac

Logiciel d'édition de code au niveau de Dieu (SublimeText3)

Comment modifier une table dans MySQL en utilisant l'instruction ALTER TABLE? Comment modifier une table dans MySQL en utilisant l'instruction ALTER TABLE? Mar 19, 2025 pm 03:51 PM

L'article discute de l'utilisation de l'instruction ALTER TABLE de MySQL pour modifier les tables, notamment en ajoutant / abandon les colonnes, en renommant des tables / colonnes et en modifiant les types de données de colonne.

Comment configurer le cryptage SSL / TLS pour les connexions MySQL? Comment configurer le cryptage SSL / TLS pour les connexions MySQL? Mar 18, 2025 pm 12:01 PM

L'article discute de la configuration du cryptage SSL / TLS pour MySQL, y compris la génération et la vérification de certificat. Le problème principal est d'utiliser les implications de sécurité des certificats auto-signés. [Compte de caractère: 159]

Comment gérez-vous les grands ensembles de données dans MySQL? Comment gérez-vous les grands ensembles de données dans MySQL? Mar 21, 2025 pm 12:15 PM

L'article traite des stratégies pour gérer de grands ensembles de données dans MySQL, y compris le partitionnement, la rupture, l'indexation et l'optimisation des requêtes.

Quels sont les outils de GUI MySQL populaires (par exemple, MySQL Workbench, PhpMyAdmin)? Quels sont les outils de GUI MySQL populaires (par exemple, MySQL Workbench, PhpMyAdmin)? Mar 21, 2025 pm 06:28 PM

L'article traite des outils de GUI MySQL populaires comme MySQL Workbench et PhpMyAdmin, en comparant leurs fonctionnalités et leur pertinence pour les débutants et les utilisateurs avancés. [159 caractères]

Comment déposez-vous une table dans MySQL à l'aide de l'instruction TABLE DROP? Comment déposez-vous une table dans MySQL à l'aide de l'instruction TABLE DROP? Mar 19, 2025 pm 03:52 PM

L'article discute de la suppression des tables dans MySQL en utilisant l'instruction TABLE DROP, mettant l'accent sur les précautions et les risques. Il souligne que l'action est irréversible sans sauvegardes, détaillant les méthodes de récupération et les risques potentiels de l'environnement de production.

Comment représentez-vous des relations en utilisant des clés étrangères? Comment représentez-vous des relations en utilisant des clés étrangères? Mar 19, 2025 pm 03:48 PM

L'article discute de l'utilisation de clés étrangères pour représenter les relations dans les bases de données, en se concentrant sur les meilleures pratiques, l'intégrité des données et les pièges communs à éviter.

Comment créez-vous des index sur les colonnes JSON? Comment créez-vous des index sur les colonnes JSON? Mar 21, 2025 pm 12:13 PM

L'article discute de la création d'index sur les colonnes JSON dans diverses bases de données comme PostgreSQL, MySQL et MongoDB pour améliorer les performances de la requête. Il explique la syntaxe et les avantages de l'indexation des chemins JSON spécifiques et répertorie les systèmes de base de données pris en charge.

Comment sécuriser MySQL contre les vulnérabilités communes (injection SQL, attaques par force brute)? Comment sécuriser MySQL contre les vulnérabilités communes (injection SQL, attaques par force brute)? Mar 18, 2025 pm 12:00 PM

L'article discute de la sécurisation MySQL contre l'injection SQL et les attaques brutales à l'aide de déclarations préparées, de validation des entrées et de politiques de mot de passe solides (159 caractères)

See all articles