【问题标题】:SQLITE - Updating a single row for each unique column pairSQLITE - 为每个唯一的列对更新一行
【发布时间】:2015-01-10 21:16:21
【问题描述】:

我非常了解 SQL,这似乎是一项需要复杂查询以避免在程序循环中执行多个查询的任务。

我有一个如下表,其中“文件名”作为唯一列:

title   subtitle    filename    comment     selected

abc     123         f1.txt      abc         0
xyz     999         f2.txt      bla         0
abc     123         f3.txt      ppp         0
poc     232         f4.txt      ppp         0
xyz     220         f5.txt      ppp         0
xyz     999         f6.txt      ppp         0

对于每个唯一的(标题、副标题)对,我只需要将单行(无关紧要)的“选定”列更新为 1。这是处理查询后表格的样子:

abc     123         f1.txt      abc         1
xyz     999         f2.txt      bla         1
abc     123         f3.txt      ppp         0
poc     232         f4.txt      ppp         1
xyz     220         f5.txt      ppp         1
xyz     999         f6.txt      ppp         0

实现这一目标的最佳方法是什么?

【问题讨论】:

    标签: sql sqlite sql-update android-sqlite


    【解决方案1】:

    首先,获取这些唯一行的 ID:

    SELECT MIN(rowid)  -- or whatever your primary key is
    FROM MyTable
    GROUP BY title, subtitle
    

    (无论你使用 MIN 还是 MAX。)

    然后更新这些行:

    UPDATE MyTable
    SET selected = 1
    WHERE rowid IN (SELECT MIN(rowid)
                    FROM MyTable
                    GROUP BY title, subtitle)
    

    【讨论】:

      【解决方案2】:

      在 SQLite 中,我认为你可以这样做:

      update table
          set selected = 1
          where not exists (select 1
                            from table t2
                            where t2.name < t.name or (t2.name = t.name and t2.title < t.title)
                           );
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-06-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多