2013-04-24 68 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 = ?;