通过SQL查询删除行 - 任何加速此查询的方法?

时间:2014-03-29 20:45:48

标签: sql sql-server

DELETE from Users 
Where Id in (
    SELECT TOP 200 u.id
    FROM users u JOIN
         playlists pl
         ON u.id = pl.UserId LEFT OUTER JOIN
         playlistitems pli
         ON pli.PlaylistId = pl.id
    GROUP BY u.id
    HAVING count(pl.id) = 1 AND
           count(pli.id) = 0
)

这个SQL查询中是否有任何陷阱会导致它运行得非常慢?删除200行需要1m32s,但我需要清理260,000个..

3 个答案:

答案 0 :(得分:1)

索引ID列上的每个表。最好是聚集索引,但不是必需的。

鉴于您已经拥有索引,请尝试以下方法:

;with cte as 
(
    select 
        u.id,
        rank() over (partition by u.id) as rk
    from users u
    join playlists pl on pl.UserId = u.ID
    join playlistites pli on pli.PlaylistID = pl.ID
)
delete from cte
where rk > 200

答案 1 :(得分:1)

我认为加入users为什么不这样做是没有意义的:

DELETE from Users 
Where Id in (
    SELECT TOP 200 pl.UserId
    FROM playlists pl
         LEFT OUTER JOIN
         playlistitems pli
         ON pli.PlaylistId = pl.id
    GROUP BY pl.UserId
    HAVING count(pl.id) = 1 AND
           count(pli.id) = 0
)

答案 2 :(得分:0)

-- insert users to delete in #temp table
SELECT u.id
INTO #toDelete
FROM users u JOIN
     playlists pl
     ON u.id = pl.UserId LEFT OUTER JOIN
     playlistitems pli
     ON pli.PlaylistId = pl.id
GROUP BY u.id
HAVING count(pl.id) = 1 AND
       count(pli.id) = 0


-- increment or decrement at will
set @rowcount 200
select 'dummy' -- force @@rowcount > 0
while @@rowcount > 0
begin

   delete 
   from Users 
   where exists (select * from #toDelete td where td.id = users.id)

end
set @rowcount 0