如果我们在where条件下传递变量,MySQL查询会很慢

如果我们在where条件下传递变量,MySQL查询会很慢,mysql,Mysql,这很慢,需要1.003秒 set @POSTCODE = 'SL2 1AT'; select latitude, longitude from postcode.postcodelatlng where postcode = @POSTCODE; select latitude, longitude from postcode.postcodelatlng where postcode = 'SL2 1AT'; 这很快,耗时0.127秒 set @POSTCODE = 'SL2 1AT';

这很慢,需要1.003秒

set @POSTCODE = 'SL2 1AT';
select latitude, longitude from postcode.postcodelatlng where postcode = @POSTCODE;
select latitude, longitude from postcode.postcodelatlng where postcode = 'SL2 1AT';
这很快,耗时0.127秒

set @POSTCODE = 'SL2 1AT';
select latitude, longitude from postcode.postcodelatlng where postcode = @POSTCODE;
select latitude, longitude from postcode.postcodelatlng where postcode = 'SL2 1AT';
表格创建语句

CREATE TABLE `postcodelatlng` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `postcode` varchar(8) NOT NULL,
  `latitude` decimal(18,15) NOT NULL,
  `longitude` decimal(18,15) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `id_postcode` (`postcode`),
  KEY `latLong` (`latitude`,`longitude`) USING BTREE
) ENGINE=MyISAM AUTO_INCREMENT=1738245 DEFAULT CHARSET=latin1;
你能帮个忙吗,为什么会发生这种情况,我们能做些什么来解决这个问题。

:=


第一行缺少一个冒号

首先,我建议您使用InnoDB而不是MyISAM。 与latin1字段相比,会产生相当大的性能开销。 您可以使用以下命令来代替

SET @POSTCODE:= CONVERT('SL2 1AT' USING latin1);

如果您的客户机是utf8,但您的表是latin1。现在查询的运行速度与我预期的一样快。

Hi Ankit,谢谢您的回复。这个表是只读的,没有发生插入更新,所以我使用MyISAM引擎来处理这个表。这个表中只有180万条记录。让我试试你提到的其他几点。