Created
May 19, 2016 01:59
-
-
Save mageddo/90cd344488a318e09e3e898ad1692399 to your computer and use it in GitHub Desktop.
Remover itens duplicados considerando uma chave que se repete
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* schema */ | |
| CREATE TABLE `item` ( | |
| `id` int(11) NOT NULL AUTO_INCREMENT, | |
| `name` varchar(45) DEFAULT NULL, | |
| `user_id` varchar(45) NOT NULL, | |
| PRIMARY KEY (`id`) | |
| ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1; | |
| CREATE TABLE `user` ( | |
| `name` varchar(45) NOT NULL, | |
| `id` int(11) NOT NULL AUTO_INCREMENT, | |
| PRIMARY KEY (`id`), | |
| UNIQUE KEY `id_UNIQUE` (`id`) | |
| ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1; | |
| INSERT INTO `item` VALUES (1,'Bola','1'),(2,'Bola','2'),(3,'Bicicleta','1'); | |
| INSERT INTO `user` VALUES ('ELVIS',1),('BRUNA',2); | |
| /* queries */ | |
| -- | |
| -- pega todos os itens já relacionados com os usuários | |
| -- porém removendo os itens duplicados (o nome do item como chave) | |
| SELECT user_id, u.name, item_id, item_name FROM( | |
| (SELECT i.name AS item_name, MIN(i.id) AS item_id FROM item i GROUP BY i.name) i1 | |
| INNER JOIN item i2 ON i1.item_id = i2.id | |
| INNER JOIN user u ON i2.user_id = u.id | |
| ); | |
| -- pega todos os items removendo os duplicados, | |
| -- o caso pegando o primeiro que encontrar e desconsiderando os outros duplicados | |
| -- (o nome do item como chave) | |
| SELECT i.name AS item_name, MIN(i.id) AS id FROM item i GROUP BY i.name; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment