gpt4 book ai didi

MYSQL - NOT 与 var=false

转载 作者:IT王子 更新时间:2023-10-28 23:44:22 26 4
gpt4 key购买 nike

在过去的几天里,我注意到一些奇怪的优化我的查询。我有一个简单的查询,它执行类似的操作:

   SELECT id,name,amount FROM reservations WHERE NOT canceled ORDER BY name ASC

我注意到 mysql 没有使用任何索引,所以我开始做一些实验。不小心我用“canceled=false”替换了“NOT cancelled”,然后,Mysql开始使用“canceled”作为索引。之后我尝试使用相反的方法:

   SELECT ... FROM reservations WHERE canceled ORDER BY ...

同样的结果!当我将其更改为“canceled=true”时,索引再次工作。

我的问题是:怎么会这样?!使用“NOT”不是“优雅”的方式吗?无论如何,我没想到它会产生任何影响。

我使用 InnoDB 作为引擎,但我使用 MyISAM 得到相同的结果。有人可以澄清一下吗?谢谢。

编辑:表结构

CREATE TABLE `reservations` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`trip_code` varchar(10) DEFAULT NULL,
`departure_date` date DEFAULT NULL,
`amount` float DEFAULT NULL,
`name` varchar(45) DEFAULT NULL,
`canceled` tinyint(1) NOT NULL DEFAULT '0',
`created_date` date NOT NULL,
`creator_user` int(11) NOT NULL DEFAULT '1',
`last_update_user` int(11) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`),
KEY `trip_code` (`trip_code`),
KEY `departure_date` (`departure_date`),
KEY `created_date` (`created_date`),
KEY `canceled` (`canceled`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=123181 ;

最佳答案

即使它使用索引,索引(信不信由你)可能会使您的查询变慢。这有点奇怪,但它与索引选择性有关。它通常显示在 bool 类型的列中。

描述如下:

"How different values of a field are. It is a number from 0-1, although you can also think of it as a percentage. A value of 1, or 100%, means that each value in the field is unique"

考虑一下很重要,因为:

"MySQL has a cost-based optimizer. This means that MySQL calculates the costs of different ways of performing a query and then chooses the cheapest one. Well, calculating the costs is an inexact science. So an estimate is taken, and the estimate is wrong sometimes."

简单明了:

如果您正在查找的数据或多或少具有相同值的 20%(例如,cancelled 有 40% 的表),那么只需进行表扫描即可。

编辑:

关于您的问题,EXPLAIN 告诉您 MySQL 正在使用索引。但是,它可能并不好,唯一能注意到你的优化是否更好的方法就是测试性能。此外,请考虑 INSERT、UPDATE 和 DELETE 操作以保留该索引的成本。使用和不使用索引进行一些分析。

看看这个:

关于MYSQL - NOT 与 var=false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8034979/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com