删除单个用户除最旧的20之外的所有行

时间:2017-02-01 04:28:31

标签: sql postgresql

假设我有一个包含列的表:

id, username, createdat(timestamp).

除了最早的20?

之外,如何删除单个用户的所有行?

所以基本上其他用户的行应该不受影响。

我知道下面的代码是错误的,但仍然希望分享我到目前为止的内容。欢迎提出任何意见或建议。

SELECT 
    *
FROM
    tableA
WHERE
    NOT EXISTS( SELECT 
            *
        FROM
            tableA
        WHERE
            username = 'abcdefg'
        ORDER BY id ASC
        LIMIT 20)

4 个答案:

答案 0 :(得分:1)

你很亲密。

DELETE FROM
  tableA
WHERE
  id NOT IN(
    SELECT 
        id
    FROM
        tableA
    WHERE
        username = 'abcdefg'
    ORDER BY createdat ASC LIMIT 20)
  AND
    username = 'abcdefg'

答案 1 :(得分:1)

您可以尝试使用左连接DELETE进行子查询,该子查询可识别给定用途的20条记录,这些记录应删除。

DELETE a
FROM tableA a
LEFT JOIN
(
    SELECT id
    FROM tableA
    WHERE username = 'abcdefg'
    ORDER BY id
    LIMIT 20
) b
    ON a.id = b.id
WHERE b.id IS NULL AND
      a.username = 'abcdefg'

答案 2 :(得分:1)

使用deleteleft join

DELETE FROM a USING tableA a
        LEFT JOIN
    (SELECT 
        id
    FROM
        tableA
    WHERE
        username = 'abcdefg'
    ORDER BY id
    LIMIT 20) b ON a.id = b.id 
WHERE
    b.id IS NULL AND a.username = 'abcdefg';

答案 3 :(得分:1)

使用这样的公用表表达式: -

;WITH CTE 
AS
(
    SELECT *,ROW_NUMBER() OVER(PARTITION BY username ORDER BY createdat   DESC) UserLevelId
    FROM [YourTable]
)
DELETE FROM CTE
WHERE CTE.UserLevelId > 20
AND CTE.username IN (........)

希望这有帮助。