Question

Si j'ai une table parent et enfant dans MySQL liée par une clé étrangère, est-il possible d'utiliser une instruction SQL pour déplacer certaines lignes de Parent et les lignes associées de l'enfant dans des tables d'archives (par exemple Parent_archive et Child_archive) de manière atomique?

Était-ce utile?

La solution

Utiliser les transactions - leur objectif est de rendre la série de déclarations SQL Atomic.

Par exemple (pas très optimisé - peut être amélioré avec le tableau temporaire):

START TRANSACTION;

INSERT Child_Archive 
SELECT DISTINCT 
Child.* FROM Child, Parent
WHERE Child.FK = Parent.PK
  AND Parent.something=11; 

DELETE Child WHERE FK IN (
    SELECT DISTINCT PK FROM Parent WHERE Parent.something=11); 

INSERT Parent_Archive
SELECT DISTINCT * FROM Parent WHERE Parent.something=11;

DELETE Parent WHERE Parent.something=11;

COMMIT;
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top