SQL删除除了某些行之外的所有行

时间:2011-08-08 23:50:41

标签: sql sqlite

我有一个包含以下(urls)列的表:

 [id,url,visited,timestamp]
 Types:[int,string,int,long]

我想:

删除除10个未访问的优先级更高的时间戳之外的所有网址(如果访问了所有网址,则删除所有网址)

它可以在单个查询中执行此操作吗?无论如何最好的查询(查询)是做什么的?

提前致谢

2 个答案:

答案 0 :(得分:21)

我认为TOP不适用于sqlite - 需要使用LIMIT

DELETE FROM mytable WHERE id NOT IN ( 
   SELECT id FROM mytable  
   WHERE visited = false 
   ORDER BY timestamp DESC
   LIMIT 10  
   )  

答案 1 :(得分:5)

DELETE FROM tableofDeletion
WHERE
  -- Delete all items not in the following select
  -- ordered by the timestamp so we can get the top 10 
  id NOT IN (SELECT id 
             FROM tableofDeletion
             WHERE 
                 visited = 0 -- false
             ORDER BY timestamp DESC
             LIMIT 10)

我认为这可以满足您的需求。