我有两张桌子:
如果CID
在过去15分钟内没有where CID.UserID = AL.UserID
,我想对CID.UserID
表AL.RecordDate
中的所有行执行删除语句。
我没有成功尝试过......
declare @15min datetime
set @15min = dateadd(minute,-15,getdate())
Delete ConnectionID CID
inner join AuditLog as AL on CID.UserID = AL.UserID
Where AL.RecordDate < @15Min AND AL.UserID in CID.UserID
我不是编写SQL语句的专家,因此非常感谢任何建议。谢谢!
答案 0 :(得分:1)
那么,您希望不删除 在过去15分钟内有活动的任何连接? (与您在问题中尝试更接近&#34;删除任何连接的任何活动超过15分钟前&#34;)。
应该是这样的:
WITH RecentActivity as (
SELECT DISTINCT UserID FROM AuditLog
WHERE RecordDate >= DATEADD(minute,-15,GETDATE())
)
DELETE FROM CID
FROM ConnectionID CID
LEFT JOIN
RecentActivity RA
on
CID.UserID= RA.UserID
WHERE
RA.UserID is NULL
答案 1 :(得分:1)
您可以像这样使用NOT EXISTS
。
declare @min15 datetime
set @min15 = dateadd(minute,-15,getdate())
Delete CID FROM ConnectionID CID
WHERE NOT EXISTS
(
SELECT TOP 1 1 FROM AuditLog as AL
WHERE AL.UserID = CID.UserID
AND AL.RecordDate > @Min15
)