search
HomeDatabaseMysql Tutorial与MSSQL对比学习MYSQL的心得(八)--插入 更新 删除

同样的,只会讲解跟SQLSERVER不同的地方 插入 将多行查询结果插入到表中 语法 INSERT INTO table_name1(column_list1) SELECT (column_list2) FROM table_name2 WHERE (condition) INSERT INTO SELECT 在SQLSERVER里也是支持的 table_name1指定待插入数据的

同样的,只会讲解跟SQLSERVER不同的地方

插入

将多行查询结果插入到表中

语法

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

INSERT INTO SELECT 在SQLSERVER里也是支持的

table_name1指定待插入数据的表;column_list1指定待插入表中要插入数据的哪些列;table_name2指定插入数据是从

哪个表中查询出来的;column_list2指定数据来源表的查询列,该列表必须和column_list1列表中的字段个数相同,数据类型相同;

condition指定SELECT语句的查询条件

从person_old表中查询所有的记录,并将其插入到person表

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

 可以看到,插入记录成功,person_old表现在有两条记录。接下来将person_oldperson_old表中的所有记录插入到person表

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

SELECT * FROM person 

可以看到数据转移成功,这里的id字段为自增的主键,在插入时要保证该字段值的唯一性,如果不能确定,可以插入的时候忽略该字段,

只插入其他字段的值

如果再执行一次就会出错

MYSQL和SQLSERVER的区别:

区别一

当要导入的数据中有重复值的时候,MYSQL会有三种方案

方案一:使用 ignore 关键字
方案二:使用 replace into
方案三:ON DUPLICATE KEY UPDATE

第二和第三种方案这里不作介绍,因为比较复杂,而且不符合要求,这里只讲第一种方案

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;

 

可以看到插入成功

SQLSERVER

在SQLSERVER这边,如果要忽略重复键,需要在建表的时候指定 WITH (IGNORE_DUP_KEY = ON) ON [PRIMARY]

这样在插入重复值的时候,SQLSERVER第一次会保留值,第二次发现有重复值的时候,SQLSERVER就会忽略掉

区别二

插入自增列时的区别

SQLSERVER需要使用 SET IDENTITY_INSERT 表名 ON 才能把自增字段的值插入到表中,如果不加 SET IDENTITY_INSERT 表名 ON

则在插入数据到表中时,不能指定自增字段的值,则id字段不能指定值,SQLSERVER会自动帮你自动增加一

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

而MYSQL则不需要,而且自由度非常大

你可以将id字段的值指定为NULL,MYSQL会自动帮你增一

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

 


也可以指定值

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

也可以不写id的值,MYSQL会自动帮你增一

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

你可以指定id字段的值也可以不指定,指定的时候只要当前id字段列没有你正在插入的那个值就可以,即没有重复值就可以

自由度非常大,而且无须指定 SET IDENTITY_INSERT 表名 ON 选项

区别三

唯一索引的NULL值重复问题

MYSQL

在MYSQL中UNIQUE 索引将会对null字段失效

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

 
上面的插入语句是可以重复插入的(联合唯一索引也一样)

SQLSERVER

SQLSERVER则不行

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 person SET info ='police' 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 ('amy',12,'bb')

SELECT * FROM person

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

SHOW TABLE STATUS LIKE 'person'

总结

这一节介绍了MYSQL里的的插入、更新和删除,并且比较了与SQLSERVER的区别,特别是MYSQL里插入语句的灵活性

刚刚开始从SQLSERVER转过来可能会有一些不适应

如有不对的地方,欢迎大家拍砖o(∩_∩)o

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
Explain the role of InnoDB redo logs and undo logs.Explain the role of InnoDB redo logs and undo logs.Apr 15, 2025 am 12:16 AM

InnoDB uses redologs and undologs to ensure data consistency and reliability. 1.redologs record data page modification to ensure crash recovery and transaction persistence. 2.undologs records the original data value and supports transaction rollback and MVCC.

What are the key metrics to look for in an EXPLAIN output (type, key, rows, Extra)?What are the key metrics to look for in an EXPLAIN output (type, key, rows, Extra)?Apr 15, 2025 am 12:15 AM

Key metrics for EXPLAIN commands include type, key, rows, and Extra. 1) The type reflects the access type of the query. The higher the value, the higher the efficiency, such as const is better than ALL. 2) The key displays the index used, and NULL indicates no index. 3) rows estimates the number of scanned rows, affecting query performance. 4) Extra provides additional information, such as Usingfilesort prompts that it needs to be optimized.

What is the Using temporary status in EXPLAIN and how to avoid it?What is the Using temporary status in EXPLAIN and how to avoid it?Apr 15, 2025 am 12:14 AM

Usingtemporary indicates that the need to create temporary tables in MySQL queries, which are commonly found in ORDERBY using DISTINCT, GROUPBY, or non-indexed columns. You can avoid the occurrence of indexes and rewrite queries and improve query performance. Specifically, when Usingtemporary appears in EXPLAIN output, it means that MySQL needs to create temporary tables to handle queries. This usually occurs when: 1) deduplication or grouping when using DISTINCT or GROUPBY; 2) sort when ORDERBY contains non-index columns; 3) use complex subquery or join operations. Optimization methods include: 1) ORDERBY and GROUPB

Describe the different SQL transaction isolation levels (Read Uncommitted, Read Committed, Repeatable Read, Serializable) and their implications in MySQL/InnoDB.Describe the different SQL transaction isolation levels (Read Uncommitted, Read Committed, Repeatable Read, Serializable) and their implications in MySQL/InnoDB.Apr 15, 2025 am 12:11 AM

MySQL/InnoDB supports four transaction isolation levels: ReadUncommitted, ReadCommitted, RepeatableRead and Serializable. 1.ReadUncommitted allows reading of uncommitted data, which may cause dirty reading. 2. ReadCommitted avoids dirty reading, but non-repeatable reading may occur. 3.RepeatableRead is the default level, avoiding dirty reading and non-repeatable reading, but phantom reading may occur. 4. Serializable avoids all concurrency problems but reduces concurrency. Choosing the appropriate isolation level requires balancing data consistency and performance requirements.

MySQL vs. Other Databases: Comparing the OptionsMySQL vs. Other Databases: Comparing the OptionsApr 15, 2025 am 12:08 AM

MySQL is suitable for web applications and content management systems and is popular for its open source, high performance and ease of use. 1) Compared with PostgreSQL, MySQL performs better in simple queries and high concurrent read operations. 2) Compared with Oracle, MySQL is more popular among small and medium-sized enterprises because of its open source and low cost. 3) Compared with Microsoft SQL Server, MySQL is more suitable for cross-platform applications. 4) Unlike MongoDB, MySQL is more suitable for structured data and transaction processing.

How does MySQL index cardinality affect query performance?How does MySQL index cardinality affect query performance?Apr 14, 2025 am 12:18 AM

MySQL index cardinality has a significant impact on query performance: 1. High cardinality index can more effectively narrow the data range and improve query efficiency; 2. Low cardinality index may lead to full table scanning and reduce query performance; 3. In joint index, high cardinality sequences should be placed in front to optimize query.

MySQL: Resources and Tutorials for New UsersMySQL: Resources and Tutorials for New UsersApr 14, 2025 am 12:16 AM

The MySQL learning path includes basic knowledge, core concepts, usage examples, and optimization techniques. 1) Understand basic concepts such as tables, rows, columns, and SQL queries. 2) Learn the definition, working principles and advantages of MySQL. 3) Master basic CRUD operations and advanced usage, such as indexes and stored procedures. 4) Familiar with common error debugging and performance optimization suggestions, such as rational use of indexes and optimization queries. Through these steps, you will have a full grasp of the use and optimization of MySQL.

Real-World MySQL: Examples and Use CasesReal-World MySQL: Examples and Use CasesApr 14, 2025 am 12:15 AM

MySQL's real-world applications include basic database design and complex query optimization. 1) Basic usage: used to store and manage user data, such as inserting, querying, updating and deleting user information. 2) Advanced usage: Handle complex business logic, such as order and inventory management of e-commerce platforms. 3) Performance optimization: Improve performance by rationally using indexes, partition tables and query caches.

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)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

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.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

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

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.