Home Database Mysql Tutorial MySQL5.7虚拟列实现表达式索引_MySQL

MySQL5.7虚拟列实现表达式索引_MySQL

May 30, 2016 pm 05:10 PM
index expression

MySQL自古以来就不提供函数索引这么复杂的功能。那怎么在MySQL里面实现这样的功能呢? 我们先来看看函数索引的概念。函数索引,也可称为表达式索引,也就是基于字段以特定函数(表达式)建立索引来提升查询性能之需。函数索引的优势在于更加精确的获取所需要的数据。


MySQL 5.7提供了一个新的特性,虚拟列,可以很完美的解决这个问题。
在介绍虚拟列之前,我们来看看在MySQL里面普通索引的范例。
示例表结构:

CREATE TABLE t1 (id INT ,rank INT, log_time DATETIME, nickname VARCHAR(64)) ENGINE INNODB;
ALTER TABLE t1 ADD PRIMARY KEY (id), ADD KEY idx_rank (rank),ADD KEY idx_log_time (log_time);
Copy after login



示例表数据量,这里我增加了5000条记录:
mysql> select count(*) from t1;
+----------+
| count(*) |
+----------+
|     5000 |
+----------+
1 row in set (0.00 sec)
Copy after login




假设我们来检索2015年4月9号的数据。(结果是有两条记录,id 分别为95和3423。)


mysql> SELECT * FROM t1 WHERE DATE(log_time) = '2015-04-09'\G
*************************** 1. row ***************************
      id: 95
    rank: 24
log_time: 2015-04-09 05:53:13
nickname: test
*************************** 2. row ***************************
      id: 3423
    rank: 42
log_time: 2015-04-09 02:55:38
nickname: test
2 rows in set (0.01 sec)
Copy after login




下来我们看看这条语句的查询计划。

mysql> explain SELECT * FROM t1 WHERE DATE(log_time) = '2015-04-09'\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: t1
   partitions: NULL
         type: ALL
possible_keys: NULL
          key: NULL
      key_len: NULL
          ref: NULL
         rows: 5000
     filtered: 100.00
        Extra: Using where
1 row in set, 1 warning (0.00 sec)
Copy after login



我们发现TYPE是ALL,扫描的函数是5000,也就是说这条语句进行了一个全表扫描。 虽然给字段log_time 加了索引,但是没有用到,那这个时候怎么办?
在MySQL里面一般这样修改:
mysql> SELECT * FROM t1 WHERE log_time >= &#39;2015-04-09 00:00:00&#39; AND log_time <=&#39;2015-04-10 00:00:00&#39;\G
*************************** 1. row ***************************
      id: 3423
    rank: 42
log_time: 2015-04-09 02:55:38
nickname: test
*************************** 2. row ***************************
      id: 95
    rank: 24
log_time: 2015-04-09 05:53:13
nickname: test
2 rows in set (0.00 sec)
Copy after login




通过查询结果,发现结果集一致,那再来看看查询计划




mysql> explain SELECT * FROM t1 WHERE log_time >= &#39;2015-04-09 00:00:00&#39; AND log_time <= &#39;2015-04-10 00:00:00&#39;\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: t1
   partitions: NULL
         type: range
possible_keys: idx_log_time
          key: idx_log_time
      key_len: 6
          ref: NULL
         rows: 2
     filtered: 100.00
        Extra: Using index condition
1 row in set, 1 warning (0.00 sec)
Copy after login




可以看到这条修改过的语句很好的利用到了idx_log_time这条索引。


那好,这个是之前在MySQL 5.6以及之前的旧版本解决方法,随着MySQL 5.7的发布,虚拟列的出现让这个问题更加简单。
现在修改下之前的表结构:


ALTER TABLE t1 ADD COLUMN log_date  DATE AS (DATE(log_Time)) stored, ADD KEY idx_log_date (log_date);
Copy after login




这样,增加了一新列,用来存放date(log_time)这个表达式,并且给他加了一列索引。


那么,之前的语句就变成如下:
mysql> SELECT * FROM t1 WHERE log_date = &#39;2015-04-09&#39;\G
*************************** 1. row ***************************
      id: 95
    rank: 24
log_time: 2015-04-09 05:53:13
nickname: test
log_date: 2015-04-09
*************************** 2. row ***************************
      id: 3423
    rank: 42
log_time: 2015-04-09 02:55:38
nickname: test
log_date: 2015-04-09
2 rows in set (0.00 sec)
Copy after login




执行后结果集和之前的一致。


我们来看看查询计划,发现很好的利用了idx_log_date索引列。
mysql> explain  SELECT * FROM t1 WHERE log_date = &#39;2015-04-09&#39;\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: t1
   partitions: NULL
         type: ref
possible_keys: idx_log_date
          key: idx_log_date
      key_len: 4
          ref: const
         rows: 2
     filtered: 100.00
        Extra: NULL
1 row in set, 1 warning (0.00 sec)
Copy after login



通过以上介绍,我们看到虚拟列实现起来相对之前的方法来的容易的多。但是这里笔者还是得说上几句。
函数索引的用法以及SQL语句虽然写起来简单,但是在大部分场合下,只能说不得已而为之,是一种设计上的缺陷,后期增加了运维人员的运维难度以及繁琐度。这也就是为什么MySQL 直到5.7才推出了这项类似的功能的原因。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to fix 100% disk usage on Windows 11 How to fix 100% disk usage on Windows 11 Apr 20, 2023 pm 12:58 PM

How to Fix 100% Disk Usage on Windows 11 The straightforward way to find the problematic application or service causing 100% disk usage is to use Task Manager. To open Task Manager, right-click on the Start menu and select Task Manager. Click the Disk column header to see what's using the most resources. From there, you'll have a good idea of ​​where to start. However, the problem may be more serious than simply closing an application or disabling a service. Read on to find more potential causes of problems and how to fix them. Disabling SuperfetchSuperfetch feature (also known as SysMain in Windows 11) helps reduce startup time by accessing prefetch files

How to hide files and folders and remove them from search in Windows 11? How to hide files and folders and remove them from search in Windows 11? Apr 26, 2023 pm 11:07 PM

&lt;h2&gt;How to Hide Files and Folders from Search on Windows 11&lt;/h2&gt;&lt;p&gt;The first thing we need to look at is customizing the location of Windows Search files. By skipping these specific locations, you should be able to see results faster while also hiding any files you want to protect. &lt;/p&gt;&lt;p&gt;If you want to exclude files and folders from searches on Windows 11, use the following steps: &lt;/p&gt;&lt;ol&

Here are 6 ways to fix Windows 11 search bar not available. Here are 6 ways to fix Windows 11 search bar not available. May 08, 2023 pm 10:25 PM

If your search bar isn't working in Windows 11, there are a few quick ways to get it up and running in no time! Any Microsoft operating system can experience glitches from time to time, and the latest operating systems are not exempt from this rule. Additionally, as pointed out by user u/zebra_head1 on Reddit, the same error appears on Windows 11 with 22H2Build22621.1413. Users complained that the option to toggle the taskbar search box randomly disappeared. Therefore, you must be prepared for any situation. Why can't I type in the search bar on my computer? The inability to type on the computer can be attributed to different factors and processes. Here are some things you should be aware of: Ctfmon.

What are the Oracle index types? What are the Oracle index types? Nov 16, 2023 am 09:59 AM

Oracle index types include: 1. B-Tree index; 2. Bitmap index; 3. Function index; 4. Hash index; 5. Reverse key index; 6. Local index; 7. Global index; 8. Domain index ; 9. Bitmap connection index; 10. Composite index. Detailed introduction: 1. B-Tree index is a self-balancing tree data structure that can efficiently support concurrent operations. In Oracle database, B-Tree index is the most commonly used index type; 2. Bit Graph index is an index type based on bitmap algorithm and so on.

Windows 11 Outlook Search Not Working: 6 Fixes Windows 11 Outlook Search Not Working: 6 Fixes Apr 22, 2023 pm 09:46 PM

Run the Search and Indexing Troubleshooter in Outlook One of the more straightforward fixes you can start is to run the Search and Indexing Troubleshooter. To run the troubleshooter on Windows 11: Click the Start button or press the Windows key and select Settings from the menu. When Settings opens, select System > Troubleshooting > Additional Troubleshooting. Scroll down on the right side, find SearchandIndexing and click the Run button. Select Outlook Search to return no results and continue with the on-screen instructions. When you run it, the troubleshooter will automatically identify and fix the problem. After running the troubleshooter, open Outlook and see if the search is working properly. like

How to solve the problem that the index exceeds the array limit How to solve the problem that the index exceeds the array limit Nov 15, 2023 pm 05:22 PM

The solutions are: 1. Check whether the index value is correct: first confirm whether your index value exceeds the length range of the array. The index of the array starts from 0, so the maximum index value should be the array length minus 1; 2. Check the loop boundary conditions: If you use the index for array access in a loop, make sure the loop boundary conditions are correct; 3. Initialize the array: Before using an array, make sure that the array has been initialized correctly; 4. Use exception handling: You can use the exception handling mechanism in the program to catch errors where the index exceeds the bounds of the array, and handle it accordingly.

PHP returns the string from the start position to the end position of a string in another string PHP returns the string from the start position to the end position of a string in another string Mar 21, 2024 am 10:31 AM

This article will explain in detail how PHP returns the string from the start position to the end position of a string in another string. The editor thinks it is quite practical, so I share it with you as a reference. I hope you will finish reading this article. You can gain something from this article. Use the substr() function in PHP to extract substrings from a string. The substr() function can extract characters within a specified range from a string. The syntax is as follows: substr(string,start,length) where: string: the original string from which the substring is to be extracted. start: The index of the starting position of the substring (starting from 0). length (optional): The length of the substring. If not specified, then

How to improve the efficiency of data grouping and data aggregation in PHP and MySQL through indexes? How to improve the efficiency of data grouping and data aggregation in PHP and MySQL through indexes? Oct 15, 2023 am 11:39 AM

How to improve the efficiency of data grouping and data aggregation in PHP and MySQL through indexes? Introduction: PHP and MySQL are currently the most widely used programming languages ​​and database management systems, and are often used to build web applications and process large amounts of data. Data grouping and data aggregation are common operations when processing large amounts of data, but if indexes are not designed and used appropriately, these operations can become very inefficient. This article will introduce how to use indexes to improve the efficiency of data grouping and data aggregation in PHP and MySQL, and improve

See all articles