我有一个数据库,人们可以通过命令发送信息并将其存储在数据库中。同一个人每天可以有许多报告,下一个查询仅显示最新的报告:
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
但是现在我想删除除上一个查询返回的记录以外的所有记录,该怎么办?
答案 0 :(得分:0)
编辑:我已将查询从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
)
答案 1 :(得分:0)
理想情况下,您会按照一组步骤进行操作,但是可以通过以下方法将其单步执行:
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