从数据库中删除,除了那个过滤器

4xrmg8kj  于 2021-06-17  发布在  Mysql
关注(0)|答案(2)|浏览(306)

我有一个数据库,人们通过命令发送信息并将其存储在数据库中。同一个人每天可以有许多报告,下一个查询只显示最新的报告:

SELECT
    r1.id,
    r1.nickname,
    r1.fecha,
    r1.bestia1,
    r1.bestia2,
    r1.bestia3,
    r1.bestia4,
    r1.bestia5
FROM
    reporte AS r1
INNER JOIN
    ( SELECT
          nickname,
          MAX(fecha) AS max_date
      FROM
          reporte
      GROUP BY
          nickname ) AS latests_reports ON latests_reports.nickname = r1.nickname AND latests_reports.max_date = r1.fecha
ORDER BY
    r1.fecha DESC

但是现在我想删除除上次查询返回的记录之外的所有记录,我该怎么做呢?

vsmadaxz

vsmadaxz1#

理想情况下,您可以将此作为一组步骤来完成,但也可以通过以下步骤来完成:

DELETE FROM reporte
WHERE id not in
(
  SELECT a.id FROM(
    SELECT r1.id
    FROM reporte AS r1 
    INNER JOIN ( SELECT nickname, MAX(fecha) AS max_date 
    FROM reporte GROUP BY nickname ) AS latests_reports 
    ON latests_reports.nickname = 
    r1.nickname AND latests_reports.max_date = r1.fecha 
  ) a
)

您需要在那里使用a.id查询,否则mysql会抱怨它不能更新reporte表
作为单独的步骤:

CREATE TABLE to_keep AS
    SELECT r1.id
    FROM reporte AS r1 
    INNER JOIN 
    ( SELECT nickname, MAX(fecha) AS max_date FROM reporte GROUP BY nickname ) AS latests_reports 
    ON 
      latests_reports.nickname = r1.nickname AND 
      latests_reports.max_date = r1.fecha

    DELETE r.* FROM reporte r LEFT JOIN to_keep k ON r.id = k.id WHERE k.id IS NULL

    DROP TABLE to_keep
wxclj1h5

wxclj1h52#

编辑:我已从更新了查询 EXITS()NOT EXISTS() 您想删除除查询中列出的记录以外的所有记录。这是您的问题:

DELETE FROM Reporte WHERE NOT EXISTS 
        (
            SELECT 1 FROM
            (
                SELECT r1.id, 
                FROM reporte AS r1 
                INNER JOIN ( SELECT nickname, MAX(fecha) AS max_date  FROM reporte GROUP BY nickname ) AS latests_reports  
                    ON latests_reports.nickname =  r1.nickname 
                    AND latests_reports.max_date = r1.fecha 
            ) r WHERE Reporte.Id= r.Id
        )

相关问题