简体   繁体   English

SQL Server删除记录

[英]SQL Server delete records

I have two tables computers , and softwareinstalls . 我有两台台式computers ,和softwareinstalls

Computers primary key is computerid, softwareinstalls has three fields (installid, computerid, and lastmodifieddate). 计算机的主键是computerid,软件安装具有三个字段(installid,computerid和lastmodifieddate)。

Software installs computerid joined with computers.computerid. 软件将安装与computers.computerid结合在一起的computerid。

I'm trying to delete all softwareinstalls on a computer that have a last modified date more than 1 day before the max for that computer, so... 我正在尝试删除最后修改日期超过该计算机的最大值之前1天的计算机上的所有软件安装,因此...

software installs table 软件安装表

install  computerid  lastmodifieddate
1        1           01-16-13
2        1           01-16-13
3        1           01-14-13
4        2           01-12-13
5        2           01-10-13

would delete records 3 and 5. what would be the query in sql server? 将删除记录3和5。在SQL Server中的查询是什么?

You can join on delete statements. 您可以加入删除语句。 Use LEFT JOIN on this. 在此上使用LEFT JOIN

DELETE  a
FROM    softwareinstalls a
        LEFT JOIN
        (
            SELECT computerID, max(lastmodifieddate) max_date
            FROM softwareinstalls
            GROUP BY computerID
        ) b ON a.computerID = b.computerID AND
                a.lastmodifieddate = b.max_date
WHERE   b.computerID IS NULL

For better performance, add an index on columns computerID and lastmodifieddate . 为了获得更好的性能,请在列computerIDlastmodifieddate上添加索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM