2013-04-24 31 views
0

我有一个MySQL查询,它是工作,但是当涉及到160万个处决,这不符合我需要的性能,因为NOT EXIST(new query)如何用JOIN重写这个语句,使其更快?

INSERT INTO `votes` (`representatives_rID`, `events_eID`, `voteResult`) 
SELECT `representatives`.`rID`,`events`.`eID`,? 
FROM `representatives`, `events` 
WHERE `events`.`eventDateTime` = ? 
AND `representatives`.`rID` = ? 
AND NOT EXISTS (SELECT * FROM `votes` 
       WHERE `votes`.`representatives_rID` = `representatives`.`rID` 
       AND `votes`.`events_eID` = `events`.`eID`); 

不断重新执行在原理图:

if (input one is in `representatives` AND input two is in `events` AND there is no row in `votes` that contains (`votes`.`representatives_rID` = `representatives`.`rid` and `votes`.`events_eID` = `events`.`eID)) { 
    insert a row into votes containing `eid` from `events` and `rid` from `representatives` and input three; 
} 

有没有什么办法可以加快速度?

+0

。 。你应该使用JOIN和GROUP BY和COUNT,并将你的“WHERE NOT EXISTS”改为“WHERE nVotes = 0”。我会稍后发布样本。 – 2013-04-24 16:19:22

+0

@Diego Nunes。我准备好被说服,但那不*听起来*非常正统或高效!好的老式OUTER JOIN如何?甚至是一个简单的IGNORE!?!? – Strawberry 2013-04-24 16:20:40

+0

@Strawberry我不知道我是否以与你相同的方式得到问题。我想他只是想避免子查询。 “分组”上的“有”应该这样做。 – 2013-04-24 16:32:34

回答

2
INSERT IGNORE INTO votes 
(representatives_rID 
,events_eID 
,voteResult 
) 
SELECT r.rID 
    , e.eID 
    , ? 
    FROM representatives r 
CROSS 
    JOIN events e 
    ON e.eventDateTime = ? 
    AND r.rID = ?;