Deleting value using SQlite while doing an INNER JOIN

萝らか妹 提交于 2019-12-18 08:52:10

问题


I am trying to delete all voters from a voters table where they are not registered as a democrat or republican AND only voted once. I have a database with three tables, congress_members, voters, and votes and have to JOIN votes with voters in order to delete the right data.

This code finds the data I want to delete:

SELECT voters.*
FROM voters JOIN votes ON voters.id = votes.voter_id
WHERE party = 'green' OR party = 'na' OR party = 'independent'
GROUP BY votes.voter_id
HAVING COUNT(*) = 1;

But I am unable to delete it because I am getting an error everytime I try to delete with a JOIN statement


回答1:


You can phrase this as a delete with a where clause:

delete from voters
    where votes.party not in ('democrat', 'republican') and
          voters.id in (select id from votes group by id having count(*) = 1);



回答2:


You are getting the error because the join will query your database and create a temporary table that will hold your newly queried data. The delete staements are used to remove data that is stored inside your database on your disk and not inside your memory.

The delete statement syntax is "DELETE FROM table WHERE conditions". The table value will need to be one of the three tables in your database, and your target is voters. As of right now, you have half of your delete statement complete.

The where clause needs to evaluate to a boolean value for each row. There is a function called EXISTS (). This function can be used to delete this data. Essentially, you will place your select statement from your post inside of the EXISTS (). The function will compare each of your rows in the target delete table to a row in your table inside of exists. If there is a match, then the row exists, the function evaluates to true for that row, and it is deleted.

DELETE FROM voters WHERE (party = 'green' OR party = 'na' OR party = 'independent') AND EXISTS ( SELECT 1 FROM votes WHERE votes.id = voters.id HAVING COUNT(*) = 1 )



来源:https://stackoverflow.com/questions/18709405/deleting-value-using-sqlite-while-doing-an-inner-join

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