【问题标题】:Deleting specific rows - SQLite删除特定行 - SQLite
【发布时间】:2019-12-20 04:34:19
【问题描述】:

我正在尝试使用 cte 从与外科医生姓名“Lucille Torres”关联的表“exchange_transactions”中删除重复行。 transaction_id 列应该是唯一的,但在这种情况下是重复的,因此尝试删除它们。我尝试了这段代码,但它似乎不起作用。将 'DELETE' 替换为 'SELECT *' 会显示我想要删除的所有行。我做错了什么?

WITH cte AS (
    SELECT 
        transaction_id,
        surgeon,  
        ROW_NUMBER() OVER (
            PARTITION BY 
                transaction_id
        ) row_num
        FROM exchange_transactions)
DELETE FROM cte
WHERE surgeon = 'Lucille Torres' AND row_num > 1

【问题讨论】:

    标签: sql sqlite common-table-expression sql-delete dbeaver


    【解决方案1】:

    使用ROWID 列获取您不会删除的每个transaction_id 的最小值:

    delete from exchange_transactions
    where surgeon = 'Lucille Torres'
    and exists (
      select 1 from exchange_transactions t
      where t.surgeon = exchange_transactions.surgeon
        and t.transaction_id = exchange_transactions.transaction_id 
        and t.rowid < exchange_transactions.rowid
    )
    

    【讨论】:

      【解决方案2】:

      直接从 CTE 中删除在 SqLite 中不起作用。

      但如果该表有一个主键(例如id
      然后可以在删除中使用 CTE 的结果。

      例如:

      WITH CTE_DUPS AS
      (
        SELECT id,
        ROW_NUMBER() OVER (
            PARTITION BY surgeon, transaction_id
            ORDER BY id) AS rn
        FROM exchange_transactions
        WHERE surgeon = 'Lucille Torres'
      )
      DELETE 
      FROM exchange_transactions
      WHERE id IN (select id from CTE_DUPS where rn > 1)
      

      测试 dbfiddle here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-07
        相关资源
        最近更新 更多