Deleting rows from SQLite table when no match exists in another table

感情迁移 提交于 2019-11-27 01:18:45

问题


I need to delete rows from an SQLite table where their row IDs do not exist in another table. The SELECT statement returns the correct rows:

SELECT * FROM cache LEFT JOIN main ON cache.id=main.id WHERE main.id IS NULL;

However, the delete statement generates an error from SQLIte:

DELETE FROM cache LEFT JOIN main ON cache.id=main.id WHERE main.id IS NULL;

The error is: SQLite Error 1 - near "left": syntax error. Is there another syntax I could use?


回答1:


SQLite apparently doesn't support joins with the delete statement, as you can see on the Syntax diagrams. You should however be able to use a subquery to delete them.

ie.

DELETE FROM cache WHERE id IN
(SELECT cache.id FROM cache LEFT JOIN main ON cache.id=main.id WHERE main.id IS NULL);

(Not tested)




回答2:


Since you going down the route of subquery, might as well get rid of the join altogether and simplify the query:

DELETE FROM cache WHERE id NOT IN (SELECT id from main);


来源:https://stackoverflow.com/questions/4967135/deleting-rows-from-sqlite-table-when-no-match-exists-in-another-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!