Home Database Mysql Tutorial MySQL enum type instance test

MySQL enum type instance test

Nov 30, 2017 am 11:05 AM
enum mysql test

What is enum? enum is the abbreviation of E.164 Number URI Mapping. Behind this abbreviation lies a great idea: the ability to use the same phone number anywhere in the world via the best and cheapest routing. You can register an ENUM number just like you would a domain name.

When developing projects, we usually encounter some status fields, such as the status of an order pending payment, paid, closed, refunded, etc. In the projects I worked on before, these statuses were stored in the database as numbers. in php Constants are used in the code to maintain a mapping table, for example:

const STATUS_PENDING = 0;
const STATUS_PAID = 1;
const STATUS_CLOSED = 2;
const STATUS_REFUNDED = 3;
Copy after login

However, in actual use, it is found that it is not so easy to use. Due to various reasons (tracking bugs, temporary statistical requirements, etc.) we often need Log in to the mysql server and manually execute some sql Query, since many tables have status fields, you must write SQL according to the mapping relationship in the PHP code. If you are not careful, you may confuse the status numbers of different tables, causing big problems.

So I planned to use the enum type of mysql to store various states in the new project. During the use, I found that if I use the Any changes to the enum type table (even changes to non-enum type fields) will result in an error

[Doctrine\DBAL\DBALException]
Unknown database type enum requested, Doctrine\DBAL\Platforms\MySQL57Platform may not support it.
Copy after login

After searching, I found that doctrine does not support mysql's enum. The article lists 3 shortcomings of enum:

When adding an enum value, you need to rebuild the entire table, which may take several hours when the amount of data is large.

enum values ​​are sorted in the order specified when creating the table structure, not by the size of the literal value.

It is not necessary to rely on mysql to verify the enum value. Inserting illegal values ​​under the default configuration will eventually become a null value.

According to the actual situation of the new project, it is unlikely that there will be a need to sort the status fields. Even if there is, we can set the order when designing the table structure, so Disadvantage 2 can be ignored; and Disadvantage 3 It can be avoided through code specifications, verification before inserting/updating, etc.; as for disadvantage 1, we need to do some testing.

Test preparation

#First create a table:

CREATE TABLE `enum_tests` (
 `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `status` enum('pending','success','closed') COLLATE utf8mb4_unicode_ci NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
Copy after login

Then insert 100W pieces of data:

$count = 1000000;
$bulk = 1000;
$data = [];
foreach (['pending', 'success', 'closed'] as $status) {
  $data[$status] = [];
  for ($i = 0; $i < $bulk; $i++) {
    $data[$status][] = [&#39;status&#39; => $status];
  }
}
  
for ($i = 0; $i < $count; $i += $bulk) {
  $status = array_random([&#39;pending&#39;, &#39;success&#39;, &#39;closed&#39;]);
  EnumTest::insert($data[$status]);
Copy after login

Test process

#Test 1

#Add a value refunded at the end of the enum value list

ALTER TABLE `enum_tests` CHANGE `status` `status` ENUM(&#39;pending&#39;,&#39;success&#39;,&#39;closed&#39;,&#39;refunded&#39;) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL;
Copy after login


Output:

Query OK, 0 rows affected (0.04 sec)
Records: 0 Duplicates: 0 Warnings: 0
Copy after login


Conclusion: There is almost no cost when appending enum values ​​at the end.

Test 2:

#Delete the value just added refunded

ALTER TABLE `enum_tests` CHANGE `status` `status` ENUM(&#39;pending&#39;,&#39;success&#39;,&#39;closed&#39;) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL;
Copy after login
Copy after login


Output:

Query OK, 1000000 rows affected (5.93 sec)
Records: 1000000 Duplicates: 0 Warnings: 0
Copy after login


Conclusion: Deleting an unused enum value still requires a full table scan, which is more expensive, but still within an acceptable range.

Test 3:

#Insert refunded into the middle of the value list instead of at the end

ALTER TABLE `enum_tests` CHANGE `status` `status` ENUM(&#39;pending&#39;,&#39;success&#39;,&#39;refunded&#39;, &#39;closed&#39;) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL;
Copy after login


Output:

Query OK, 1000000 rows affected (6.00 sec)
Records: 1000000 Duplicates: 0 Warnings: 0
Copy after login


Conclusion: Adding a new value in the middle of the original enum value list requires scanning and updating the entire table, which is costly.

Test 4:

#Delete the value in the middle of the value list

ALTER TABLE `enum_tests` CHANGE `status` `status` ENUM(&#39;pending&#39;,&#39;success&#39;,&#39;closed&#39;) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL;
Copy after login
Copy after login


Output:

Query OK, 1000000 rows affected (4.23 sec)
Records: 1000000 Duplicates: 0 Warnings: 0
Copy after login


Conclusion: A full table scan is required and the cost is high.

Test 5:

#Add an index to the status field and then execute the above test

ALTER TABLE `enum_tests` ADD INDEX(`status`);
Copy after login


Discover the time consumption of tests 2-4 On the contrary, it has increased, which should be caused by the need to update the index at the same time.

Conclusion:

#For my new project, only new enum values ​​will appear. Even if some states are abandoned in the future, there is no need to adjust the enum value list, so Decided to introduce enum into the project Type serves as a data type for storing state.

Related recommendations:

Detailed explanation of Enum (enumeration) usage in php

Enum extended feature example code

How to solve the confusion about the default value of enum data type

The above is the detailed content of MySQL enum type instance test. For more information, please follow other related articles on the PHP Chinese website!

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)

MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

How to start mysql by docker How to start mysql by docker Apr 15, 2025 pm 12:09 PM

The process of starting MySQL in Docker consists of the following steps: Pull the MySQL image to create and start the container, set the root user password, and map the port verification connection Create the database and the user grants all permissions to the database

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

Solve database connection problem: a practical case of using minii/db library Solve database connection problem: a practical case of using minii/db library Apr 18, 2025 am 07:09 AM

I encountered a tricky problem when developing a small application: the need to quickly integrate a lightweight database operation library. After trying multiple libraries, I found that they either have too much functionality or are not very compatible. Eventually, I found minii/db, a simplified version based on Yii2 that solved my problem perfectly.

How to install mysql in centos7 How to install mysql in centos7 Apr 14, 2025 pm 08:30 PM

The key to installing MySQL elegantly is to add the official MySQL repository. The specific steps are as follows: Download the MySQL official GPG key to prevent phishing attacks. Add MySQL repository file: rpm -Uvh https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm Update yum repository cache: yum update installation MySQL: yum install mysql-server startup MySQL service: systemctl start mysqld set up booting

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

MySQL and phpMyAdmin: Core Features and Functions MySQL and phpMyAdmin: Core Features and Functions Apr 22, 2025 am 12:12 AM

MySQL and phpMyAdmin are powerful database management tools. 1) MySQL is used to create databases and tables, and to execute DML and SQL queries. 2) phpMyAdmin provides an intuitive interface for database management, table structure management, data operations and user permission management.

Centos install mysql Centos install mysql Apr 14, 2025 pm 08:09 PM

Installing MySQL on CentOS involves the following steps: Adding the appropriate MySQL yum source. Execute the yum install mysql-server command to install the MySQL server. Use the mysql_secure_installation command to make security settings, such as setting the root user password. Customize the MySQL configuration file as needed. Tune MySQL parameters and optimize databases for performance.

See all articles