Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
MYSQL: Eliminar duplicados mediante JOIN - https://es.stackoverflow.co...
Language:
Ada
Assembly
Bash
C#
C++ (gcc)
C++ (clang)
C++ (vc++)
C (gcc)
C (clang)
C (vc)
Client Side
Clojure
Common Lisp
D
Elixir
Erlang
F#
Fortran
Go
Haskell
Java
Javascript
Kotlin
Lua
MySql
Node.js
Ocaml
Octave
Objective-C
Oracle
Pascal
Perl
Php
PostgreSQL
Prolog
Python
Python 3
R
Rust
Ruby
Scala
Scheme
Sql Server
Swift
Tcl
Visual Basic
Layout:
Vertical
Horizontal
/*MYSQL: Eliminar duplicados mediante JOIN - https://es.stackoverflow.com/q/148640/29967*/ /* -- ATENCIÓN NO USE DROP TABLE CON SUS TABLAS REALES -- YA QUE DROP TABLE BORRARÁ SUS DATOS -- DROP TABLE SE USA AQUÍ SÓLO PARA PODER PROBAR LOS DATOS */ DROP TABLE IF EXISTS usuarios; DROP TABLE IF EXISTS usuarios_copy; /* NO COPIE LA SENTENCIA ^ DROP TABLE ^ EN SUS DATOS REALES */ -- I. Datos de prueba CREATE TABLE usuarios ( id INT PRIMARY KEY AUTO_INCREMENT, first_name VARCHAR(50) NOT NULL, last_name VARCHAR(50) NOT NULL, email VARCHAR(255) NOT NULL ); INSERT INTO usuarios (first_name,last_name,email) VALUES ('Pedro ','Pérez','p.pedro@gmail.com'), ('Juan','Roa','r.juan@icloud.com'), ('Santiago','Guerrero','g.santiago@hotmail.com'), ('Juan','Roa','r.juan@icloud.com'), ('Andrés ','Brito','b.andres@live.com'), ('Juan','Roa','r.juan@icloud.com'), ('Santiago','Guerrero','g.santiago@hotmail.com'), ('Felipe','Castro','c.felipe@me.com') ; /* Prueba de datos antes de borrar*/ SELECT id, email FROM usuarios ORDER BY email; -- II. Borrar mediante JOIN DELETE t1 FROM usuarios t1 INNER JOIN usuarios t2 WHERE t1.id > t2.id AND t1.email = t2.email; /* Prueba de datos después de borrar*/ SELECT id, email FROM usuarios ORDER BY id; -- III. Restringir duplicados ALTER TABLE usuarios ADD UNIQUE (email); /* Prueba de la nueva restricción creada: al descomentar el código tendremos el siguiente error: Error(s), warning(s): Duplicate entry 'p.pedro@gmail.com' for key 'email' */ -- INSERT INTO usuarios (first_name,last_name,email) VALUES ('Pedro ','Pérez','p.pedro@gmail.com');
absolute service time: 0,37 sec
edit mode
|
history
id
email
1
5
b.andres@live.com
2
8
c.felipe@me.com
3
3
g.santiago@hotmail.com
4
7
g.santiago@hotmail.com
5
1
p.pedro@gmail.com
6
2
r.juan@icloud.com
7
4
r.juan@icloud.com
8
6
r.juan@icloud.com
id
email
1
1
p.pedro@gmail.com
2
2
r.juan@icloud.com
3
3
g.santiago@hotmail.com
4
5
b.andres@live.com
5
8
c.felipe@me.com