连接两个独立的表与第三个连接结果在MySQL中

时间:2014-04-17 12:18:33

标签: mysql join subquery union

我的数据库大小增加到10GB以上,现在我需要重新考虑我的查询。它们是一种快速而肮脏的解决方案,但现在需要进行大量优化。我将非常感谢您的帮助和讨论。

我有三张桌子。

  1. 投票(Voter_ID,CandidateID) - 投票给谁(约8 GB)的商店

  2. 建议(Voter_ID,CandidateID) - 推荐谁(约3 GB)的商店 (选民可以投票和推荐。)

  3. 候选人(CandidateID,Election_time,Candidate_Party)(约100 MB)

  4. 我需要从这些数据中找到很多信息。第一部分是找到候选人党的死忠粉丝。我们需要获得该党的所有候选人,然后获得他们的选民和推荐人的ID。

    当前查询如下:

    select 
    Voter_ID, 
    sum(votes) as vote_count,
    sum(recos) as reco_count,
    sum(votes) + sum(recos)) as total
     from 
    ((select Voter_ID, 
    count(CandidateID) as votes, 0 as recos from votes,
    recommendations 
    where CandidateID=CandidateID 
    and Candidate_Party in ('abcd') 
    and Election_time >= '2013-01-01'
    and Election_time <='2014-01-1' 
    group by Voter_ID) 
    
    UNION ALL 
    
    (select 
    Voter_ID, 
    0 as votes, 
    count(CandidateID) as recos 
    from 
    votes, 
    recommendations 
    where 
    CandidateID=CandidateID and 
    Candidate_Party in ('abcd') and 
    Election_time >= '2013-01-01' and Election_time <='2014-01-1' 
    group by Voter_ID)
    ) as usercount group by Voter_ID 
    order by total desc
    

    我希望我能更好地格式化它。但是我的数据库查询速度非常慢。有索引,但数据大小杀死我的服务器3GB的RAM。我真的想最充分地优化这个查询,然后根据需要添加RAM。提前感谢您的回答。

0 个答案:

没有答案