为什么这个MYSQL更新查询需要2分钟才能运行?

为什么这个MYSQL更新查询需要2分钟才能运行?,mysql,sql,Mysql,Sql,执行此查询几乎需要2分钟(更改9条记录): 单独执行此查询需要0.0030秒: SELECT t2.another_id FROM table2 t2 WHERE ((t2.id_parent = 2658 AND t2.year = 2016) OR (t2.id = 2658 AND t2.year = 2016)) 并以整数形式返回3行 以下是关于这两个表的信息: CREATE TABLE IF NOT EXISTS `table1` ( `another_id`

执行此查询几乎需要2分钟(更改9条记录):

单独执行此查询需要0.0030秒:

SELECT t2.another_id 
FROM table2 t2
WHERE ((t2.id_parent = 2658 AND t2.year = 2016) 
       OR (t2.id = 2658 AND t2.year = 2016))
并以整数形式返回3行

以下是关于这两个表的信息:

CREATE TABLE IF NOT EXISTS `table1` 
(
  `another_id` int(11) NOT NULL,
  `table1_id` int(11) NOT NULL,
  `code_group` varchar(1) DEFAULT NULL,
  `code_id` int(10) DEFAULT NULL,
  PRIMARY KEY (`another_id`,`table1_id`),
  KEY `another_id` (`another_id`),
  KEY `code_group` (`code_group`,`code_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

CREATE TABLE IF NOT EXISTS `table2` 
(
  `id_year` int(11) NOT NULL,
  `id` int(11) NOT NULL,
  `id_parent` int(11) DEFAULT NULL,
  `another_id` int(11) NOT NULL,
  `code_group` varchar(1) DEFAULT NULL,
  `code_id` int(10) DEFAULT NULL,
  PRIMARY KEY (`id_year`,`id`),
  KEY `id_parent` (`id_year`,`id_parent`)
  KEY `another_id` (`another_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_polish_ci;

有没有人可以告诉我为什么执行此查询需要2分钟

您可以使用内部联接进行如下更新:t2.year也不存在

UPDATE table1 t1
INNER JOIN table2 t2 ON t2.another_id = t1.another_id
    AND ((t2.id_parent= 2658 AND t2.year= 2016) OR (t2.id= 2658 AND t2.year= 2016))
SET t1.code_id = NULL, t1.code_group = NULL 

中的
有时会妨碍优化。我首先将子查询直接放在
FROM
子句中:

UPDATE table1 t1 JOIN
       (SELECT t2.another_id 
        FROM table2 t2
        WHERE ((t2.id_parent= 2658 AND t2.year= 2016) OR
               (t2.id= 2658 AND t2.year= 2016)
              )
       ) t2
       ON t1.another_id = t2.another_id
    SET t1.code_id = null,
        t1.code_group = null;

然后,看看这个查询,我建议在
table1(另一个id)
上建立一个索引。事实上,该索引可能足以满足您最初的查询。

为什么((t2.id_parent=2658和t2.year=2016)在或中两次?根据我的经验,使用Explain查看您需要索引的位置MySQL有时似乎在优化不相关的子查询时遇到问题,因此它们似乎会针对每一行再次执行。在您的情况下,我建议在单独的查询中运行subselect,然后在应用程序中动态使用结果创建实际查询应用程序。尝试使用索引对其进行优化。创建非聚集索引…
table2
没有列
t2。另一个\u id
。MySQL将加入其中,因此它与哪一列相关。虽然我仍然无法找到主要问题的合理答案(两个表上已经有“另一个\u id”的索引),您的解决方案非常有效。将2分钟的查询转换为0.0040秒的查询。谢谢;)@JacMar。您的问题的答案是,
中的
有时会妨碍优化。嘿,我无法执行此查询。MySQL在第2行返回sytax错误。我已经根据MySQL更新了查询。顺便说一句,我在T2中没有得到年份列。
UPDATE table1 t1 JOIN
       (SELECT t2.another_id 
        FROM table2 t2
        WHERE ((t2.id_parent= 2658 AND t2.year= 2016) OR
               (t2.id= 2658 AND t2.year= 2016)
              )
       ) t2
       ON t1.another_id = t2.another_id
    SET t1.code_id = null,
        t1.code_group = null;