MySQL enum type instance 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;
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.
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;
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][] = ['status' => $status]; } } for ($i = 0; $i < $count; $i += $bulk) { $status = array_random(['pending', 'success', 'closed']); EnumTest::insert($data[$status]);
Test process
#Test 1
#Add a value refunded at the end of the enum value list
ALTER TABLE `enum_tests` CHANGE `status` `status` ENUM('pending','success','closed','refunded') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL;
Output:
Query OK, 0 rows affected (0.04 sec) Records: 0 Duplicates: 0 Warnings: 0
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('pending','success','closed') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL;
Output:
Query OK, 1000000 rows affected (5.93 sec) Records: 1000000 Duplicates: 0 Warnings: 0
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('pending','success','refunded', 'closed') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL;
Output:
Query OK, 1000000 rows affected (6.00 sec) Records: 1000000 Duplicates: 0 Warnings: 0
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('pending','success','closed') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL;
Output:
Query OK, 1000000 rows affected (4.23 sec) Records: 1000000 Duplicates: 0 Warnings: 0
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`);
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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.

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 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.

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.

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

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 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.

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.
