简体   繁体   English

我们可以在MySQL 5.7中在包含NULL值的列上创建索引吗?

[英]Can we create an index on a column containing NULL values in MySQL 5.7?

Following is the text from the MySQL Documentation : 以下是MySQL文档中的文本:

The primary key for a table represents the column or set of columns that you use in your most vital queries. 表的主键代表您在最重要的查询中使用的一列或一组列。 It has an associated index, for fast query performance. 它具有关联的索引,可提高查询性能。 Query performance benefits from the NOT NULL optimization, because it cannot include any NULL values . 查询性能得益于NOT NULL优化,因为它不能包含任何NULL值

I am not understanding the exact meaning of the sentence in bold font from the above text. 从上面的文本中,我不理解该粗体字句的确切含义。 Someone please explain to me. 有人请向我解释。

Also, let me know whether can we create an index on a column containing NULL values in MySQL 5.7 ? 另外,让我知道我们是否可以在MySQL 5.7中包含NULL值的列上创建索引? If no, what's the reason? 若否,原因何在?

Thank You. 谢谢。

A PRIMARY key is used to organize the data on disk and because there is a relationship to how the data is physically arranged you cannot have any part of a primary key being NULL. PRIMARY键用于组织磁盘上的数据,并且由于与数据的物理排列方式有关系,因此主键的任何部分都不能为NULL。

A non-primary index CAN have one or more columns that allow NULLs. 非主索引可以具有一个或多个允许为NULL的列。 demo 演示

CREATE TABLE `my_docs` (
  `id` int(6) unsigned NOT NULL AUTO_INCREMENT,
  `rev` int(3) ,
  `content` varchar(200) NOT NULL,
  PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;


INSERT INTO `my_docs` (`rev`, `content`) VALUES
  (1, 'The earth is flat'),
  (1, 'One hundred angels can dance on the head of a pin'),
  (NULL, 'The earth is flat and rests on a bull\'s horn'),
  (3, 'The earth is like a ball.');

alter table `my_docs` add key my_added_index (`rev`);

SELECT id, rev, content
FROM `my_docs`
where rev = 3

| id | rev |                   content |
|----|-----|---------------------------|
|  4 |   3 | The earth is like a ball. |


+---+-------------+-----------+------+----------------+----------------+---------+-------+------+----------+-------+
| d | select_type |   table   | type | possible_keys  |      key       | key_len |  ref  | rows | filtered | Extra |
+---+-------------+-----------+------+----------------+----------------+---------+-------+------+----------+-------+
| 1 |    SIMPLE   |   my_docs | ref  | my_added_index | my_added_index |       5 | const |    1 |   100.00 |       |
+---+-------------+-----------+------+----------------+----------------+---------+-------+------+----------+-------+

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

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