繁体   English   中英

MySQL个索引的使用

[英]Usage of MySQL indexes

我有一个非常简单的表格,有五列,

CREATE TABLE notification_tag (
    _id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    notification_id INT NOT NULL,
    tag_value CHAR(11) NOT NULL,
    recipient CHAR(11) NOT NULL,
    brand CHAR(11),

    INDEX tag_value (tag_value),
    INDEX notification_id_tag_value_recipient_brand (notification_id, tag_value, recipient, brand)
) CHARACTER SET ascii COLLATE ascii_bin;

当我运行以下查询时,Explain 显示 MySQL 正在使用键tag_value

select * from notification_tag
where recipient='user' and tag_value='doc1' and (brand='brand' or brand is null);
+--+-----------+----------------+----------+-------------------------------------------------------------+----+---------+-------+-----+----+--------+-----------+
|id|select_type|table           |partitions|possible_keys                                                |type|key      |key_len|ref  |rows|filtered|Extra      |
+--+-----------+----------------+----------+-------------------------------------------------------------+----+---------+-------+-----+----+--------+-----------+
|1 |SIMPLE     |notification_tag|NULL      |tag_value,notification_id_tag_value_recipient_brand|ref |tag_value|11     |const|1   |100     |Using where|
+--+-----------+----------------+----------+-------------------------------------------------------------+----+---------+-------+-----+----+--------+-----------+

有什么理由不使用notification_id_tag_value_recipient_brand索引吗?

您的查询将不会使用(notification_id, tag_value, recipient, brand)上的索引,因为该查询没有任何术语来搜索索引的最左边的列。

想想一本电话簿。 如果您按姓氏或按姓氏和名字搜索人员,这会有所帮助。 但是,如果您仅按名字搜索,则书中条目的顺序无济于事。

您可能还喜欢我的演示文稿How to Design Indexes, Really视频

暂无
暂无

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

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