选择并更新查询并查找重复项

时间:2016-05-12 18:14:35

标签: mysql sql inner-join

大家好!我正在尝试编写查询以查找内容的副本并设置除原始文章之外的所有重复项(原始文章将由计数器定义(如果原始帖子的计数器大于所有其他重复计数器,则它是原始文件)并在数据库中设置为active = 0.

DB achitecture{id, title (varchar), description(varchar), img(varchar), active(int)}

以下查询用于查找重复项

  SELECT posts.title, posts.counter, posts.id
  FROM posts
  INNER JOIN (
  SELECT title
  FROM posts
  GROUP BY title
  HAVING count(title) > 1
  ) duplicates ON posts.title = duplicates.title
  ORDER BY posts.title;

我需要为重复项设置active = 0 怎么做?

1 个答案:

答案 0 :(得分:1)

您可以随时将其转换为UPDATE JOIN

UPDATE posts INNER JOIN
       (SELECT title, MAX(counter) as maxcounter
        FROM posts
        GROUP BY title
        HAVING count(title) > 1
       ) duplicates
       ON posts.title = duplicates.title AND posts.counter < maxcounter
    set posts.active = 0;