CREATE TABLE `products` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`brand` int(11) DEFAULT NULL,
`shown` tinyint(4) DEFAULT '1',
PRIMARY KEY (`id`),
KEY `fk_products_brandId_idx` (`brand`),
KEY `pk_products_shown` (`shown`),
CONSTRAINT `fk_products_brandId` FOREIGN KEY (`brand`) REFERENCES `brands` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_products_categoryId` FOREIGN KEY (`category`) REFERENCES `categories` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
我有这个"显示"字段,用于标记已删除的记录(如果用户删除记录,则不会删除;这些字段设置为值0)。
因此我或多或少的所有查询都是这样的:
"SELECT * FROM products WHERE brand = 1 AND shown = 1"
但如果我在MySQL / oracle Workbench中解释它,那就说全表扫描。显然它是有道理的,因为99%的数据库记录显示= 1,但品牌也有一个索引。
这是工作台输出的解释
{
"query_block": {
"select_id": 1,
"cost_info": {
"query_cost": "2.40"
},
"table": {
"table_name": "products",
"access_type": "ALL",
"possible_keys": [
"fk_products_brandId_idx",
"pk_products_shown"
],
"rows_examined_per_scan": 7,
"rows_produced_per_join": 2,
"filtered": "40.82",
"cost_info": {
"read_cost": "1.83",
"eval_cost": "0.57",
"prefix_cost": "2.40",
"data_read_per_join": "6K"
},
"used_columns": [
"id",
"name_bg",
"name_en",
"category",
"weight",
"width",
"length",
"height",
"brand",
"availability",
"text_bg",
"text_en",
"sold",
"price",
"price_retail",
"linked_products",
"created_at",
"created_by",
"updated_at",
"updated_by",
"shown"
],
"attached_condition": "((`whatever`.`products`.`shown` = 1) and (`whatever`.`products`.`brand` = 18))"
}
}
}
我的逻辑是错误的,或者我的显示索引是否已被修改,以便普通查询不会进行全表扫描?
mysql 5.7
答案 0 :(得分:4)
在(brand, shown)
上创建复合索引。该索引将使用brand = constant AND shown=1
以及brand=constant
上的过滤器加速查询。
ALTER TABLE products ADD INDEX brand_shown (brand, shown);
此索引还会加快表单
的查询SELECT * FROM products WHERE brand >= 1 AND brand <=10 AND shown = 1;
或
SELECT * FROM products WHERE brand BETWEEN 1 AND 10 AND shown = 1;
做好索引编制需要一些知识。阅读https://use-the-index-luke.com/是一种很好的学习方式。
MySQL可能正在进行全表扫描,因为shown
的基数 - 不同值的数量 - 非常低。所以它猜测表扫描比试图弄清楚如何从索引获取数据要便宜。
如果您可以将查询修改为
SELECT name FROM products WHERE brand = constant AND shown = 1
然后将name
添加到索引中,您将拥有a so-called covering index。这将允许MySQL仅通过对索引进行范围扫描来满足您的查询,并且速度非常快。
ALTER TABLE products ADD INDEX brand_shown_name (brand, shown, name);
专业提示在性能有问题的查询中避免使用SELECT *
。而是列出您需要的列。当你这样做时,MySQL可能会应用一些优化(比如覆盖索引优化)。
专业提示2 避免仅为了衡量标准而创建索引。创建查询实际需要的(或强制唯一性)。额外的索引占用空间并减慢INSERT和UPDATE操作。