L
L
Lavrov952018-05-28 20:27:26
SQL
Lavrov95, 2018-05-28 20:27:26

How to delete all data from the database where the value matches, leave the sense of one?

table `cities`

id | name
1  | moscow
2  |  washington
3  |  washington

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Rsa97, 2018-05-28
@Lavrov95

DELETE `c1`.*
  FROM `cities` AS `c1`
  JOIN `cities` AS `c2` ON `c2`.`name` = `c1`.`name`
    AND `c2`.`id` < `c1`.`id`

A
Artem, 2018-05-28
@devspec

Something like this

P
profaller, 2018-05-28
@profaller

For example:

DELETE
FROM cities
WHERE id NOT IN (

  SELECT id
  FROM (
         SELECT t1.id

         FROM cities t1

           LEFT JOIN (
                       SELECT id
                       FROM cities
                       GROUP BY name
                     ) t2 ON t1.id = t2.id

         WHERE t2.id IS NOT NULL
       ) tmp
)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question