简体   繁体   English

简单选择查询优化

[英]simple select query optimise

I have a table defined as follows: 我有一个定义如下的表:

   CREATE TABLE IF NOT EXISTS `cards` (
`ID` int(11) NOT NULL,
  `Name` varchar(200) NOT NULL,
  `WorkerID` varchar(20) NOT NULL,
  `pic` varchar(200) NOT NULL,
  `expDate` bigint(20) NOT NULL,
  `reminderSent` tinyint(4) NOT NULL,
  `regNum` varchar(8) NOT NULL,
  `cardType` varchar(200) NOT NULL
) ENGINE=MyISAM AUTO_INCREMENT=92 DEFAULT CHARSET=latin1;


ALTER TABLE `cards`
 ADD PRIMARY KEY (`ID`), ADD KEY `cardsWorkerID_idx` (`WorkerID`);

But running: 但是运行:

explain
SELECT pic, expDate, Name, ID, cardType, regNum FROM cards WHERE workerID= 18

tells me it is scanning the entire table, even though I added an index to the workerID field. 告诉我,即使我向workerID字段添加了索引,它仍在扫描整个表。 Can anyone explain what I'm missing? 谁能解释我所缺少的吗?

The use of indexes depends on the size of the data. 索引的使用取决于数据的大小。 It also depends on the types used for the comparison. 它还取决于用于比较的类型。 If you have a small table, then the SQL engine might decide that a scan is more efficient than using the index. 如果表较小,则SQL引擎可能会决定扫描比使用索引更有效。 This is particularly true if the table fits on a single data page. 如果表适合单个数据页,则尤其如此。

In your case, though, the problem is might be data conversion. 但是,就您而言,问题可能是数据转换。 Use the appropriate typed constant for the comparison: 使用适当的类型常量进行比较:

SELECT pic, expDate, Name, ID, cardType, regNum
FROM cards
WHERE workerID = '18';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM