我有几个版本分配给DocumentID。
DocID Version
ABC 1
ABC 2
ABC 3
DEF 1
DEF 2
如何删除旧版本并保留最新版本?删除后,这应保留在表中:
DocID Version
ABC 3
DEF 2
答案 0 :(得分:6)
SQL Server 2005 +:
;WITH x AS (SELECT DocID, Version, rn = ROW_NUMBER() OVER
(PARTITION BY DocID ORDER BY Version DESC)
FROM dbo.tablename
)
DELETE x WHERE rn > 1;
对于SQL Server 2000,它有点复杂。 (包含版本信息总是有用的。)
DELETE t
FROM dbo.tablename AS t
LEFT OUTER JOIN
(
SELECT DocID, Version = MAX(Version)
FROM dbo.tablename
GROUP BY DocID
) AS t2
ON t.DocID = t2.DocID
AND t.Version = t2.Version
WHERE t2.DocID IS NULL;
显然是后一个查询will work in MySQL as well(感谢@bluefeet)。
对于MySQL,你可以自己做一个完全不同的问题。