Deleting value using SQlite while doing an INNER JOIN

dar*_*500 4 sql sqlite join sql-delete

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;
Run Code Online (Sandbox Code Playgroud)

但是我无法删除它,因为每次尝试使用JOIN语句删除时都会收到错误

Gor*_*off 7

你可以delete用a表示这个where条款:

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


Lel*_*ton 5

您收到错误是因为连接将查询您的数据库并创建一个临时表来保存您新查询的数据。删除语句用于删除存储在磁盘上的数据库中而不是内存中的数据。

delete 语句语法是“DELETE FROM table WHERE conditions”。表值需要是您数据库中的三个表之一,您的目标是选民。截至目前,您的删除语句已完成一半。

where 子句需要为每一行计算一个布尔值。有一个函数叫做EXISTS()。此功能可用于删除此数据。本质上,您将从帖子中选择语句放在 EXISTS () 中。该函数会将目标删除表中的每一行与表中存在的行进行比较。如果存在匹配项,则该行存在,该函数对该行的计算结果为真,然后将其删除。

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 )