简体   繁体   English

通过与 MySQL 的多对多关系查找未在选举中投票的选民

[英]Finding voters that did not vote in an election through a many to many relationship with MySQL

I have two tables linked through a many-to-any relationship.我有两个通过多对任意关系链接的表。 Table one contains all voters with an ID, table two contains all elections with an ID, and table three links both tables using their IDs.表一包含所有带有 ID 的选民,表二包含所有带有 ID 的选举,表三使用他们的 ID 链接两个表。

Not all voters voted in all elections.并非所有选民都在所有选举中投票。 I would like to query the many-to-many relationship to find the elections for each voter that they did not vote in. I'm using MySQL.我想查询多对多关系,以找到他们没有投票的每个选民的选举。我正在使用 MySQL。

A typical solution to this is to generate all possible combinations of voters and elections with a cross join , then try to bring the junction table with a left join : where no record matches, you know a voter missed an election.对此的典型解决方案是使用cross join联接生成选民和选举的所有可能组合,然后尝试使用left join联接引入联结表:在没有记录匹配的情况下,您知道选民错过了选举。

Consider:考虑:

select v.voter_id, e.election_id
from voters v
cross join elections e
left join voter_elections ve 
    on  ve.voter_id = v.voter_id
    and ve.election_id = e.election_id
where ve.voter_id is null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM