MySQL optimization - sample code analysis of simple syntax:
1. Default constraints
--mysql CREATE TABLE emp ( id INT DEFAULT 12 )
2. Set auto-increment columns
MYSQL's auto-increment column must be an indexed column, and the seed value must be set at the back of the table.
--mysql -- 设置自增ID从N开始 CREATE TABLE emp ( ID INT PRIMARY KEY AUTO_INCREMENT ) AUTO_INCREMENT = 100 ; --(设置自增ID从100开始)
Set the step size of the auto-increment column, which can be divided into global level and session level. If it is the session level, then when the user creates a new session, the step size returns to the global level. MySQL cannot be set to the table level step size! !
The mysql server maintains two types of mysql system parameters (system variables): global variables and session variables.
Their meanings and differences are as shown in their respective names. Session variables are at the session level, and changes to them will only affect this session; global variables are at the system level, and
changes to them will Affects all new sessions (existing sessions are not affected when changing) until the next restart of mysql server.
Note that the impact of its change cannot span restarts. If you want to use the new value when the mysql server restarts, you can only specify it by specifying variable options on the command line or changing the option file.
The change through SET is Cannot reach across restarts.
Each system variable has a default value, which is determined when compiling the mysql system.
To specify system variables, you can generally specify options on the command line when the server is started or through the option file
Of course, most system variables can be specified through the set command when the system is running. value.
View the system's current default auto-increment column seed value and step value
SHOW GLOBAL VARIABLES LIKE 'auto_incre%'; -- 全局变量
Question: If there is a table with an auto-increment primary key with the field id, when it has been added to the table After inserting 10 pieces of data, delete the data with IDs 8, 9, and 10, restart mysql, and insert another piece of data after
. What should the ID value of this piece of data be? Is it 8 or 11?
Answer: If the table type is MyISAM, then it is 11. If the type of table is InnoDB, the id is 8.
This is because the two types of storage engines store the maximum ID record in different ways. The MyISAM table records the maximum ID into the data file, and the maximum ID value of the auto-incremented primary key will not be lost when restarting mysql;
InnoDB records the maximum ID value in memory, so after restarting mysql or performing an OPTIMIZE operation on the table, the maximum ID value will be lost.
By the way, there are four ways for MYSQL to get the auto-increment value of the current table.
(1) SELECT MAX(id) FROM person 针对特定表 (2) SELECT LAST_INSERT_ID() 函数 针对任何表 (3) SELECT @@identity 针对任何表
@@identity means the latest data inserted into the table with the identity attribute (i.e. auto-increment column) The value of the corresponding auto-increment column is a system-defined global variable.
Generally, system-defined global variables start with @@, and user-defined variables start with @.
The prerequisite for using @@identity is that after performing the insert operation, the connection is not closed when executing select @@identity, otherwise the result will be a NULL value.
(4) SHOW TABLE STATUS LIKE 'person'
If you are targeting a specific table, it is recommended to use this method
In the result, there is an Auto_increment field in the corresponding table name record, and the value of the next auto-increment ID in it is the current The maximum auto-increment ID of the table.
3. View the table definition
DESC emp
4. Modify the table name
ALTER TABLE emp RENAME emp2
5. Modify the data type of the field
Change the int type of the id field to bigint
ALTER TABLE emp2 MODIFY id BIGINT
6. Modify the field name
When modifying the field name in MYSQL, you need to add the data type of the field, otherwise it will An error is reported, and CHANGE can also only modify the data type to achieve the same effect as MODIFY. The method is to set the "new field name" and "old field name" in the SQL statement to the same name, and only change the "data type". Change Data type, such as the example just now, change the id column to bigint data type
<p style="margin-bottom: 7px;">ALTER TABLE emp2 CHANGE id id BIGINT<br/></p>
7. Add fields
ALTER TABLE emp2 ADD NAME NVARCHAR(200) NULL
8. Delete fields
MYSQL delete fields There is no need to add the COLUMN keyword
ALTER TABLE emp2 DROP NAME
9. Delete foreign key constraints
If it is a foreign key constraint, you need to use DROP FOREIGN KEY. If it is a primary key constraint, you need to use DROP PRIMARY KEY.
--Delete foreign key constraints
ALTER TABLE emp2 DROP FOREIGN KEY fk_emp_dept
--Delete primary key constraints
ALTER TABLE emp2 DROP PRIMARY KEY pk_emp_dept
10. Delete table
DROP TABLE emp2
But if you want to delete it at the same time Please make a judgment first before deleting multiple tables or deleting
DROP TABLE IF EXISTS emp1 ,emp2
Supplement:
USE test; -- myisam引擎 CREATE TABLE TEST( ID int unsigned not null auto_increment, name varchar(10) not null, key(name,id))engine=MYISAM auto_increment=100 ; -- innodb引擎 CREATE TABLE TESTIdentity( ID int unsigned not null auto_increment, NID INT UNSIGNED , name varchar(10) not null, key(id))engine=INNODB auto_increment=100 ; --或者主键 CREATE TABLE TESTIdentity( ID int unsigned not null auto_increment, NID INT UNSIGNED , name varchar(10) not null, key(id))engine=INNODB auto_increment=100 ; [Database4] ErrorCode: -2147467259, Number: 1075 ErrorMessage: Incorrect table definition; there can be only one auto column and it must be defined as a key alter table TESTIdentity modify column nid int auto_increment;
No matter the innodb engine or the MYISAM engine table, there can only be one auto-increment column, and the auto-increment column The column must be an index column, whether it is a secondary index or a primary key index
The above is the detailed content of MySQL optimization - sample code analysis of simple syntax. For more information, please follow other related articles on the PHP Chinese website!

InnoDBBufferPool reduces disk I/O by caching data and indexing pages, improving database performance. Its working principle includes: 1. Data reading: Read data from BufferPool; 2. Data writing: After modifying the data, write to BufferPool and refresh it to disk regularly; 3. Cache management: Use the LRU algorithm to manage cache pages; 4. Reading mechanism: Load adjacent data pages in advance. By sizing the BufferPool and using multiple instances, database performance can be optimized.

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

MySQL is worth learning because it is a powerful open source database management system suitable for data storage, management and analysis. 1) MySQL is a relational database that uses SQL to operate data and is suitable for structured data management. 2) The SQL language is the key to interacting with MySQL and supports CRUD operations. 3) The working principle of MySQL includes client/server architecture, storage engine and query optimizer. 4) Basic usage includes creating databases and tables, and advanced usage involves joining tables using JOIN. 5) Common errors include syntax errors and permission issues, and debugging skills include checking syntax and using EXPLAIN commands. 6) Performance optimization involves the use of indexes, optimization of SQL statements and regular maintenance of databases.

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA


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

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

Atom editor mac version download
The most popular open source editor

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software