mysql - 优化mysql多字段查询

标签 mysql query-optimization

我对如何为我的表选择最佳索引感到困惑:

有这个表:

Hotel
-has_1
...
-has-5
-nota_AVG
-nota_1
-nota_2
-nota_3

还有这个

Nota_hotel
-nota_1
-nota_2
-nota_3
-id_hotel

酒店中名称为“nota_*”的字段是通过表 Nota_hotel 上的触发器进行更新的,并且该字段经常更改。

我需要做一些查询,例如

select * from hotel where has_X = true or has_Y=true order by nota_Z

我的子句“WHERE”在查询中可以有 1 个 has_X 或多个 has_* 字段,具体取决于选择的复选框。

我想知道放置索引的最佳实践是什么,为每个字段“nota_”添加索引并为字段“has_”创建单个索引(has_1,...,has_5)或为每个字段“has_”添加也有索引,如果有这么多索引可能会扼杀我的 MySQL 服务器吗?

    create table hotel(
id int primary key auto_increment,
nume varchar(255),
index hotel_nume_index(nume),
nume_oras varchar(100),
nume_zona varchar(100),
nume_tara varchar(100),
foreign key (nume_oras,nume_zona,nume_tara) references oras(nume,nume_zona,nume_tara) ON DELETE CASCADE,
descriere text,
stele int,
map_x double,
map_y double,
has_sauna TINYINT(1),
has_piscina TINYINT(1),
has_parcare TINYINT(1),
has_restaurant TINYINT(1),
has_fitness TINYINT(1),
distanta_obiectiv double,
code_api1 varchar(255),
code_api2 varchar(255),
code_api3 varchar(255),
intern TINYINT(1),
nota_hotel double,
nota_restaurant double,
nota_locatie double,
nota_conditii double,
nume_comision varchar(100),
foreign key (nume_comision) references comision(nume)
);



 create table nota_hotel(
fb_id varchar(100),
data DATETIME,
nota_restaurant double,
nota_locatie double,
nota_conditi double,
comentariu text,
nume_user varchar(255),
id_hotel int,
foreign key (id_hotel) references hotel(id) ON DELETE CASCADE
);

这是完整的定义

最佳答案

这是一个正在进行中的答案。将添加到它。

假设您有 5 个 has_ 列,例如 has_restaurant、has_pool、has_pool,并且搜索像以前一样针对 true 类型,如“它确实有一个池”

对于初学者来说,使用 2 的幂将它们转换为一列。我们称之为 hasX其列值是以下内容的按位或(不是列)

has_restaurant (2^0)   1
has_pool (2^1)   2
has_wifi (2^2)  4
has_piscina (2^3)  8
has_sauna (2^4)  16

因此,如果酒店有 wifi 和桑拿房,那么 hasX 列将(至少)包含值 20 开启的位,但也可能包含值 21(也有餐厅)。但搜索的是“我想要 wifi 和桑拿”,所以它也找到了 21。这是一个mask

此时我们已在 hasX 列上向 hotel 添加了一个索引

编辑 我只是对这个概念进行了轰炸,因为我认为我可以进行按位搜索,但在阅读完相关内容后这似乎是不可能的。以下似乎是最好的处理

CREATE TABLE hotel ( 
hotel_id int primary key auto_increment PRIMARY KEY,
/* some more fields... */ 
); 

CREATE TABLE hotel_flags ( 
flag_id TINYINT UNSIGNED NOT NULL 
, description VARCHAR(100) NOT NULL 
, PRIMARY KEY (flag_id) 
); 

**the following is the intersect table**
CREATE TABLE hotel_flags_intersect ( 
hotel_id int not null
, flag_id TINYINT UNSIGNED NOT NULL 
, PRIMARY KEY (hotel_id, flag_id) 
, UNIQUE INDEX reverse_pk (flag_id, hotel_id) 
); 

谦虚借用http://forums.mysql.com/read.php?24,35318,35640#msg-35640

关于mysql - 优化mysql多字段查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30669313/

相关文章:

mysql - 每 3 个字符串后用空格替换逗号

mysql - 在 mysql 中索引文本是否会改进使用 LIKE '%search%' 搜索文本

mysql - 优化mysql查询

MySQL:在巨大的插入后添加索引 ->更快与否

mysql - 从 node.js 返回多行

php - 无法使用 PDO 的 fetch 或 fetchAll 函数获取任何数据

php - 如何在 php 中回显输入类型

java - 使用 order by 和 limit by 子句优化 mysql 查询

MySQL - 按列值获取范围内的结果

php - 如何改善此MySQL查询?