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

标签 mysql sql performance

我有一个 mySQL 查询,它正在工作,但是当执行 160 万次时,它不能满足我需要的性能,因为NOT EXIST(新查询)不断地重新执行

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;
}

有什么办法可以让这个更快,可能是通过 join 吗?

最佳答案

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 = ?; 

关于mysql - 如何用 JOIN 重写这个语句,使其更快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16197091/

相关文章:

php - Joomla eventlist函数中的多个mysql查询

php - MySql Inner Join 不在 Google Chart 中显示数据

mysql - 我们如何访问mysql中存在于另一个数据库中的表?

c++ - 错误 : Can't connect to Mysql server on '' (10055)

MySQL存储过程INSERT问题

javascript - 使用 JavaScript 测量页面加载时间

java - C++ 和 Java 性能

mysql - mysql 中的过程

java - 如何知道一个 where 子句查询结果包含另一个 where 子句查询结果?

mysql - 性能:MySQL 中的 OR 条件会显着降低内部连接速度吗?