【问题标题】:Cleaning up database records清理数据库记录
【发布时间】:2011-01-27 22:55:11
【问题描述】:

我有一个 mysql 表,其中包含可版本化的键/值对。它有列:

Id(int,autoincrement,primary key) Key(varchar) Value(text) Version(整数)

随着给定键的值更新,版本号增加并添加新行,而不是更改现有条目。现在,这个系统已经经历了一个繁重的编辑阶段,有大量的旧版本对我来说是无用的。

我没有运气尝试构建一个 SQL 脚本,该脚本将删除表中每个键的除最高版本之外的所有版本。 非常感谢任何人的帮助。

【问题讨论】:

    标签: sql mysql database


    【解决方案1】:

    做出有希望的安全假设,即最高版本也具有最高 id。

    delete from table
    where id not in
        (select max(id)
        from table
        group by key)
    

    【讨论】:

      【解决方案2】:

      测试这个选择脚本,它应该选择所有旧版本的行。

      SELECT * FROM table o where id in (SELECT i.* FROM table i WHERE i.Version<>MAX(i.Version) and i.ID=o.ID )
      

      如果可行,那么只需将“SELECT *”替换为“DELETE”即可。请确保在删除任何内容之前备份表。

      http://www.cyberdesignworks.com.au/news-blog/web-developers-MySQL-Quick-Tips (通过SQL查看复制表)

      我的脚本没有假设最高 id 是最高版本。

      【讨论】:

        【解决方案3】:
        delete * from yourtable where id not in (select id from yourtable x where version=(select max(version) from yourtable where id=x.id))
        

        不舒尔,但应该工作! :)

        先试试这样的选择:

        select * from yourtable where id not in (select id from yourtable x where version=(select max(version) from yourtable where id=x.id)) limit 500
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-01-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-11-20
          • 1970-01-01
          相关资源
          最近更新 更多