search
HomeDatabaseMysql TutorialMySQL optimization - specific analysis of additions, deletions and modifications (picture)

MySQL optimization - specific analysis of additions, deletions and modifications (picture)

Insert

will be more Row query results are inserted into the table

Syntax

INSERT INTO table_name1(column_list1) SELECT (column_list2) FROM table_name2 WHERE (condition)

table_name1 specifies the table into which data is to be inserted; column_list1 specifies which columns in the table to be inserted into which data is to be inserted; table_name2 specifies the data to be inserted from

Which table is queried from; column_list2 specifies the query column of the data source table. This list must have the same number of fields and the same data type as the column_list1 list;

condition specifies the query condition of the SELECT statement

Query all records from the person_old table and insert them into the person table

CREATE TABLE person (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT,
  NAME CHAR(40) NOT NULL DEFAULT '',
  age INT NOT NULL DEFAULT 0,
  info CHAR(50) NULL,
  PRIMARY KEY (id)
)

CREATE TABLE person_old (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT,
  NAME CHAR(40) NOT NULL DEFAULT '',
  age INT NOT NULL DEFAULT 0,
  info CHAR(50) NULL,
  PRIMARY KEY (id)
)

INSERT INTO person_old
VALUES (11,'Harry',20,'student'),(12,'Beckham',31,'police')

SELECT * FROM person_old

You can see that the records were inserted successfully and the person_old table now has Two records. Next, insert all the records in the person_oldperson_old table into the person table

INSERT INTO person(id,NAME,age,info)
SELECT id,NAME,age,info FROM person_old;
SELECT * FROM person


You can see that the data transfer is successful. The id field here is For auto-incremented primary keys, the uniqueness of the field value must be ensured when inserting. If it is not determined, the field can be ignored when inserting.

Only insert the values ​​of other fields

If executed again An error will occur once

The difference between MYSQL and SQLSERVER:

Difference 1

When there are duplicate values ​​in the data to be imported, MYSQL will have three options

Option 1: Use the ignore keyword
Option 2: Use replace into
Option Three: ON DUPLICATE KEY UPDATE

The second and third options will not be introduced here, because they are more complicated and do not meet the requirements. Only the first option will be discussed here

TRUNCATE TABLE person

TRUNCATE TABLE persona_old 

INSERT INTO person_old
VALUES (11,'Harry',20,'student'),(12,'Beckham',31,'police')

##注意下面这条insert语句是没有ignore关键字的
INSERT  INTO person(id,NAME,age,info)
SELECT id,NAME,age,info FROM person_old;

INSERT INTO person_old 
VALUES (13,'kay',26,'student')

##注意下面这条insert语句是有ignore关键字的
INSERT IGNORE INTO person(id,NAME,age,info)
SELECT id,NAME,age,info FROM person_old;

You can see that the insertion is successful

SQLSERVER

On the SQLSERVER side, if you want to ignore duplicate keys, you need Specify WITH (IGNORE_DUP_KEY=ON) when creating the table ON [ PRIMARY]

In this way, when inserting duplicate values, SQLSERVER will retain the value for the first time, and when duplicate values ​​are found for the second time, SQLSERVER will ignore it. Get rid of

Difference 2

The difference when inserting an auto-increment column

SQLSERVER You need to use SETIDENTITY_INSERT table nameON to insert the value of the auto-increment field into the table. If you do not add SET IDENTITY_INSERT table name ON

When inserting data into the table, the value of the auto-increment field cannot be specified. The value of the id field cannot be specified. SQLSERVER will automatically increase it for you.一

INSERTINTO person(NAME,age,info) VALUES ('feicy',33,'student')

But MYSQL does not need it, and the degree of freedom is very large

you You can specify the value of the id field as NULL, and MYSQL will automatically add one for you.

INSERTINTO person(id,NAME,age,info) VALUES (NULL,'feicy',33,'student')

can also be used You can also specify the value

INSERT IGNORE INTO person(id,NAME,age,info) VALUES (16,'tom',88,'student')

without writing the value of the id. MYSQL will automatically add one for you.

INSERT IGNORE INTO person(NAME,age,info) VALUES ('amy',12,'bb')

You can specify the value of the id field or not. When specifying, as long as the current id field column does not have the value you are inserting, that is, there will be no duplicate values.

The degree of freedom is very large, and there is no need to specify SET IDENTITY_INSERT table name ON Options

Difference three

NULL value duplication problem of unique index

MYSQL

In MYSQL, the UNIQUE index will be invalid for null fields

insert into test(a) values(null)
 
insert into test(a) values(null)

The above insert statement can be inserted repeatedly (the same is true for the joint unique index)

SQLSERVER

SQLSERVER will not work

CREATE TABLE person (
  id INT  NOT NULL IDENTITY(1,1),
  NAME CHAR(40)  NULL DEFAULT '',
  age INT NOT NULL DEFAULT 0,
  info CHAR(50) NULL,
  PRIMARY KEY (id)
)

CREATE UNIQUE INDEX IX_person_unique ON [dbo].[person](name)

INSERT INTO [dbo].[person]
        ( [NAME], [age], [info] )
VALUES  ( NULL, -- NAME - char(40)
          1, -- age - int
          'aa'  -- info - char(50)
          ),
          ( NULL, -- NAME - char(40)
          2, -- age - int
          'bb'  -- info - char(50)
          )

消息 2601,级别 14,状态 1,第 1 行
不能在具有唯一索引“IX_person_unique”的对象“dbo.person”中插入重复键的行。重复键值为 (<NULL>)。
语句已终止。

Update

The update is relatively simple, not much Said

UPDATE person SET info =&#39;police&#39; WHERE id BETWEEN 14 AND 17

SELECT * FROM person



删除

删除person表中一定范围的数据


DELETE FROM  person  WHERE id BETWEEN 14 AND 17

SELECT * FROM person


如果要删除表的所有记录可以使用下面的两种方法

##方法一
DELETE     FROM person

##方法二
TRUNCATE TABLE  person

跟SQLSERVER一样,TRUNCATE TABLE会比DELETE FROM TABLE 快

MYISAM引擎下的测试结果,30行记录


跟SQLSERVER一样,执行完TRUNCATE TABLE后,自增字段重新从一开始。

################################
INSERT IGNORE INTO person(id,NAME,age,info)
SELECT id,NAME,age,info FROM person_old;

SELECT * FROM person

TRUNCATE TABLE  person


INSERT IGNORE INTO person(NAME,age,info) VALUES (&#39;amy&#39;,12,&#39;bb&#39;)

SELECT * FROM person


当你刚刚truncate了表之后执行下面语句就会看到重新从一开始

SHOW TABLE STATUS LIKE &#39;person&#39;


The above is the detailed content of MySQL optimization - specific analysis of additions, deletions and modifications (picture). For more information, please follow other related articles on the PHP Chinese website!

Statement
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
When should you use a composite index versus multiple single-column indexes?When should you use a composite index versus multiple single-column indexes?Apr 11, 2025 am 12:06 AM

In database optimization, indexing strategies should be selected according to query requirements: 1. When the query involves multiple columns and the order of conditions is fixed, use composite indexes; 2. When the query involves multiple columns but the order of conditions is not fixed, use multiple single-column indexes. Composite indexes are suitable for optimizing multi-column queries, while single-column indexes are suitable for single-column queries.

How to identify and optimize slow queries in MySQL? (slow query log, performance_schema)How to identify and optimize slow queries in MySQL? (slow query log, performance_schema)Apr 10, 2025 am 09:36 AM

To optimize MySQL slow query, slowquerylog and performance_schema need to be used: 1. Enable slowquerylog and set thresholds to record slow query; 2. Use performance_schema to analyze query execution details, find out performance bottlenecks and optimize.

MySQL and SQL: Essential Skills for DevelopersMySQL and SQL: Essential Skills for DevelopersApr 10, 2025 am 09:30 AM

MySQL and SQL are essential skills for developers. 1.MySQL is an open source relational database management system, and SQL is the standard language used to manage and operate databases. 2.MySQL supports multiple storage engines through efficient data storage and retrieval functions, and SQL completes complex data operations through simple statements. 3. Examples of usage include basic queries and advanced queries, such as filtering and sorting by condition. 4. Common errors include syntax errors and performance issues, which can be optimized by checking SQL statements and using EXPLAIN commands. 5. Performance optimization techniques include using indexes, avoiding full table scanning, optimizing JOIN operations and improving code readability.

Describe MySQL asynchronous master-slave replication process.Describe MySQL asynchronous master-slave replication process.Apr 10, 2025 am 09:30 AM

MySQL asynchronous master-slave replication enables data synchronization through binlog, improving read performance and high availability. 1) The master server record changes to binlog; 2) The slave server reads binlog through I/O threads; 3) The server SQL thread applies binlog to synchronize data.

MySQL: Simple Concepts for Easy LearningMySQL: Simple Concepts for Easy LearningApr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

MySQL: A User-Friendly Introduction to DatabasesMySQL: A User-Friendly Introduction to DatabasesApr 10, 2025 am 09:27 AM

The installation and basic operations of MySQL include: 1. Download and install MySQL, set the root user password; 2. Use SQL commands to create databases and tables, such as CREATEDATABASE and CREATETABLE; 3. Execute CRUD operations, use INSERT, SELECT, UPDATE, DELETE commands; 4. Create indexes and stored procedures to optimize performance and implement complex logic. With these steps, you can build and manage MySQL databases from scratch.

How does the InnoDB Buffer Pool work and why is it crucial for performance?How does the InnoDB Buffer Pool work and why is it crucial for performance?Apr 09, 2025 am 12:12 AM

InnoDBBufferPool improves the performance of MySQL databases by loading data and index pages into memory. 1) The data page is loaded into the BufferPool to reduce disk I/O. 2) Dirty pages are marked and refreshed to disk regularly. 3) LRU algorithm management data page elimination. 4) The read-out mechanism loads the possible data pages in advance.

MySQL: The Ease of Data Management for BeginnersMySQL: The Ease of Data Management for BeginnersApr 09, 2025 am 12:07 AM

MySQL is suitable for beginners because it is simple to install, powerful and easy to manage data. 1. Simple installation and configuration, suitable for a variety of operating systems. 2. Support basic operations such as creating databases and tables, inserting, querying, updating and deleting data. 3. Provide advanced functions such as JOIN operations and subqueries. 4. Performance can be improved through indexing, query optimization and table partitioning. 5. Support backup, recovery and security measures to ensure data security and consistency.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use