如何用JOIN重写这个语句,使其更快?

时间:2013-04-24 16:15:20

标签: mysql sql performance

我有一个mySQL查询,它正在运行,但是当涉及160万次执行时,由于NOT EXIST(new query)

的不断重新执行,它无法满足我所需的性能
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;
}

有没有办法让这更快,可能还有加入?

1 个答案:

答案 0 :(得分: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 = ?;