如何按日期和ID删除MySQL表上的重复项?

时间:2015-12-31 14:25:37

标签: mysql sql

我有一张表格,其结果来自应用。 一些结果是重复的,我可以看到哪个“survey_question_id”有重复的答案。

通过此查询,我可以看到每个“survey_question_id”有多少重复:

    SELECT `id`,`survey_question_id`,
   `question`,`date`, COUNT(*) 
   FROM answers 
   GROUP BY `survey_question_id`, `date` 
   HAVING COUNT(*) > 1 and `date` > '2015-10-15'

表格结果:

enter image description here

如何删除重复项?

3 个答案:

答案 0 :(得分:2)

你可以

  1. 创建表your_table2作为select original * from original_table 然后只是
  2. 使用一些级联约束和
  3. 删除original_table
  4. 更改your_table2,重命名并添加所有约束 只是删除original_table中的所有数据,只需插入original_table select * from your_table2
  5. 我认为this与您的问题类似。

答案 1 :(得分:0)

试试这个:

DELETE FROM answers
WHERE date > '2015-10-15'
AND id NOT IN 
  (SELECT id
      FROM (SELECT MIN(id) AS id  FROM answers
            WHERE date > '2015-10-15'
            GROUP BY survey_question_id) x
  )

答案 2 :(得分:0)

删除重复记录时,您可以使用:

如果你想保持最低ID,你可以使用它:

deg.arr <- c(atan2(y.arr, exp(x.arr)), NA)
theta <- atan2((y2 - y1) * uin[2], exp((x2 - x1)) * uin[1])

如果你想保留HIGEST id,你可以使用它:

DELETE n1 FROM answers n1, answers n2 WHERE n1.id > n2.id 
AND n1.id <> n2.id
AND n1.survey_question_id = n2.survey_question_id 
AND n1.question = n2.question 
AND n1.date = n2.date

如果您认为以后再次发生这种情况,请添加 UNIQUE INDEX

DELETE n1 FROM answers n1, answers n2 WHERE n1.id < n2.id 
AND n1.id <> n2.id
AND n1.survey_question_id = n2.survey_question_id 
AND n1.question = n2.question 
AND n1.date = n2.date

旁注:在执行任何批量删除之前,请确保您拥有此表的副本