当前位置:网站首页>[mysql_11] addition, deletion and modification of data processing
[mysql_11] addition, deletion and modification of data processing
2022-06-11 15:02:00 【CoderXiong】
1. insert data
With atguigudb.departments Table as an example
1.1 The way 1:VALUES The way to add
Using this syntax, only one piece of data can be inserted into the table at a time . situation 1: Inserts data in the default order for all fields of the table
INSERT INTO Table name VALUES (value1,value2,....);
Copy code The above insertion method needs to specify values for each field of the table , And the order of values must be the same as that of fields in the data table . give an example :
INSERT INTO departments VALUES (70, 'Pub', 100, 1700);
INSERT INTO departments VALUES(100, 'Finance', NULL, NULL);
Copy code situation 2: Insert data for the specified fields of the table
INSERT INTO Table name (column1 [, column2, …, columnn]) VALUES (value1 [,value2, …, valuen]);
Copy code Insert data for the specified fields of the table , Is in the INSERT Statement inserts values into only some fields , The values of other fields are the default values when the table is defined . stay INSERT Column names are arbitrarily listed in the clause , But once listed ,VALUES To insert value1,....valuen Need and column1,...columnn The columns correspond one by one . If the type is different , Will not be able to insert , also MySQL There will be mistakes . give an example :
INSERT INTO departments(department_id, department_name) VALUES (80, 'IT');
Copy code situation 3: Insert multiple records at the same time INSERT Statement can insert multiple records into the data table at the same time , Specify multiple value lists when inserting , Each value list is separated by commas , The basic syntax is as follows :
INSERT INTO table_name
VALUES
(value1 [,value2, …, valuen]),
(value1 [,value2, …, valuen]),
……
(value1 [,value2, …, valuen]);
Copy code perhaps
INSERT INTO table_name(column1 [, column2, …, columnn])
VALUES
(value1 [,value2, …, valuen]),
(value1 [,value2, …, valuen]),
……
(value1 [,value2, …, valuen]);
Copy code give an example :
mysql> INSERT INTO emp(emp_id,emp_name)
-> VALUES (1001,'shkstart'),
-> (1002,'atguigu'),
-> (1003,'Tom');
Query OK, 3 rows affected (0.00 sec)
Records: 3 Duplicates: 0 Warnings: 0
Copy code Use INSERT When inserting multiple records at the same time ,MySQL It will return some additional information that is not available when performing single line insertion , The meaning of this information is as follows :
- Records: Indicates the number of records inserted .
- Duplicates: Indicates the records that were ignored during insertion , The reason may be that these records contain duplicate primary key values .
- Warnings: Data values indicating a problem , For example, data type conversion occurs .
A that inserts multiple rows of records at the same time INSERT Statement is equivalent to multiple single line inserts INSERT sentence , But multi line INSERT Statement during processing More efficient . because MySQL Execute a single article INSERT Statement inserts more rows of data than using multiple INSERT Fast sentence , Therefore, when inserting multiple records, it is best to choose to use a single record INSERT Insert... In the form of a statement .
Summary :
- VALUES Or you could write it as VALUE , however VALUES It's standard writing .
- Character and date data should be enclosed in single quotes .
1.2 The way 2: Insert the query results into the table
INSERT Can also be SELECT Insert the result of the statement query into the table , At this time, it is not necessary to input the values of each record one by one , Just use one INSERT Statement and a line SELECT Statements can quickly insert multiple rows from one or more tables into a table . The basic syntax is as follows :
INSERT INTO Target table name
(tar_column1 [, tar_column2, …, tar_columnn])
SELECT
(src_column1 [, src_column2, …, src_columnn])
FROM Source table name
[WHERE condition]
Copy code To summarize the rules of this insertion :
- stay INSERT Add a subquery to the statement .
- There's no need to write VALUES Clause .
- The list of values in the subquery should be the same as INSERT The column name in Clause corresponds to .
give an example :
-- All columns
INSERT INTO emp2
SELECT *
FROM employees
WHERE department_id = 90;
-- Specify column insertion
INSERT INTO sales_reps(id, name, salary, commission_pct)
SELECT employee_id, last_name, salary, commission_pct
FROM employees
WHERE job_id LIKE '%REP%';
Copy code 2. Update data
- Use UPDATE Statement update data . The grammar is as follows :
UPDATE table_name
SET column1=value1, column2=value2, … , column=valuen
[WHERE condition]
Copy code - You can update more than one piece of data at a time .
- If you need to roll back data , It needs to be guaranteed in DML front , Set it up :
SET AUTOCOMMIT = FALSE; - Use WHERE Clause specifies the data to be updated .
UPDATE employees
SET department_id = 70
WHERE employee_id = 113;
Copy code - If omitted WHERE Clause , Then all data in the table will be updated .
UPDATE copy_emp
SET department_id = 110;
Copy code - Update data integrity error ( Foreign key constraint )
3. Delete data
- Use DELETE Statement to delete data from a table
DELETE FROM table_name [WHERE <condition>];
-- table_name Specify the table to delete ;
-- “[WHERE ]” Is an optional parameter , Specify deletion criteria , without WHERE Clause ,DELETE Statement will delete all records in the table .
Copy code - Use WHERE Clause deletes the specified record .
DELETE FROM departments WHERE department_name = 'Finance';
Copy code - If omitted WHERE Clause , All data in the table will be deleted
- Data integrity error in delete ( Foreign key constraints )
4. MySQL8 New characteristics : Calculated column
What is a calculated column ? Simply put, the value of a column is calculated from other columns . for example ,a The column value is 1、b The column value is 2,c Columns do not need to be inserted manually , Definition a+b As the result of the c Value , that c Is the calculation column , It is calculated from other columns . stay MySQL 8.0 in ,CREATE TABLE and ALTER TABLE Both support adding calculation Columns . Let's say CREATE TABLE For example . give an example : Define data table tb1, Then define the fields id、 Field a、 Field b And field c, Which field c Is a calculated column , Used to calculate a+b Value . First create a test table tb1, The statement is as follows :
CREATE TABLE tb1(
id INT,
a INT,
b INT,
c INT GENERATED ALWAYS AS (a + b) VIRTUAL
);
Copy code Insert demo data , The statement is as follows :
INSERT INTO tb1(a,b) VALUES (100,200);
Copy code Query data table tb1 Data in , give the result as follows :
mysql> SELECT * FROM tb1;
+------+------+------+------+
| id | a | b | c |
+------+------+------+------+
| NULL | 100 | 200 | 300 |
+------+------+------+------+
1 row in set (0.00 sec)
Copy code Update the data in the data , The statement is as follows :
mysql> UPDATE tb1 SET a = 500;
Query OK, 0 rows affected (0.00 sec)
Rows matched: 1 Changed: 0 Warnings: 0
Copy code 5. Comprehensive case
1、 Create database test01_library 2、 Create table books, The table structure is as follows : 3、 towards books Insert records in the table
1) Do not specify field name , Insert the first record
2) Specify all field names , Insert second record
3) Insert multiple records at the same time ( All the remaining records )
4) Type the novel (novel) The prices of all the books have increased 5.
5) Name as EmmaT Change the price of your book to 40, And change the description to drama.
6) Delete inventory as 0 The record of .
7) Included in the title of the statistical book a A Book of letters
8) Included in the title of the statistical book a The number of alphabetic books and the total stock
9) find “novel” Type of book , In descending order of price
10) Search for book information , In descending order of inventory , If the inventory is the same, follow note Ascending order
11) according to note Number of classified statistical books
12) according to note Inventory of classified statistics , Show that the inventory exceeds 30 Ben's
13) Search all books , Each page shows 5 Ben , Show second page
14) according to note Inventory of classified statistics , Displays the most in stock
15) Query the title of the book to 10 A one character book , Not including the space inside
16) Check the title and type of the book , among note The value is novel Show novel ,law Show legal ,medicine Show medicine ,cartoon Show cartoon ,joke Show jokes
17) Check the title of the book 、 stock , among num Value exceeds 30 Ben's , Show unsalable , Greater than 0 And below 10 Of , Show best sellers , by 0 The display needs to be out of stock
18) Count each note The stock of , And total
19) Count each note The number of , And total
20) Count the top three books in stock
21) Find the first book published
22) find novel The most expensive book in
23) Find the book with the most words in the title , No spaces
answer :
#1、 Create database test01_library
CREATE DATABASE IF NOT EXISTS test01_library CHARACTER SET 'utf8';
# Specify which database to use
USE test01_library;
#2、 Create table books
CREATE TABLE books(
id INT,
name VARCHAR(50),
`authors` VARCHAR(100) ,
price FLOAT,
pubdate YEAR ,
note VARCHAR(100),
num INT
);
#3、 towards books Insert records in the table
# 1) Do not specify field name , Insert the first record
INSERT INTO books
VALUES(1,'Tal of AAA','Dickes',23,1995,'novel',11);
# 2) Specify all field names , Insert second record
INSERT INTO books (id,name,`authors`,price,pubdate,note,num)
VALUES(2,'EmmaT','Jane lura',35,1993,'Joke',22);
# 3) Insert multiple records at the same time ( All the remaining records )
INSERT INTO books (id,name,`authors`,price,pubdate,note,num) VALUES
(3,'Story of Jane','Jane Tim',40,2001,'novel',0),
(4,'Lovey Day','George Byron',20,2005,'novel',30),
(5,'Old land','Honore Blade',30,2010,'Law',0),
(6,'The Battle','Upton Sara',30,1999,'medicine',40),
(7,'Rose Hood','Richard haggard',28,2008,'cartoon',28);
# 4、 Type the novel (novel) The prices of all the books have increased 5.
UPDATE books SET price=price+5 WHERE note = 'novel';
# 5、 Name as EmmaT Change the price of your book to 40, And change the description to drama.
UPDATE books SET price=40,note='drama' WHERE name='EmmaT';
# 6、 Delete inventory as 0 The record of .
DELETE FROM books WHERE num=0;
# 7、 Included in the title of the statistical book a A Book of letters
SELECT * FROM books WHERE name LIKE '%a%';
# 8、 Included in the title of the statistical book a The number of alphabetic books and the total stock
SELECT COUNT(*),SUM(num) FROM books WHERE name LIKE '%a%';
# 9、 find “novel” Type of book , In descending order of price
SELECT * FROM books WHERE note = 'novel' ORDER BY price DESC;
# 10、 Search for book information , In descending order of inventory , If the inventory is the same, follow note Ascending order
SELECT * FROM books ORDER BY num DESC,note ASC;
# 11、 according to note Number of classified statistical books
SELECT note,COUNT(*) FROM books GROUP BY note;
# 12、 according to note Inventory of classified statistics , Show that the inventory exceeds 30 Ben's
SELECT note,SUM(num) FROM books GROUP BY note HAVING SUM(num)>30;
# 13、 Search all books , Each page shows 5 Ben , Show second page
SELECT * FROM books LIMIT 5,5;
# 14、 according to note Inventory of classified statistics , Displays the most in stock
SELECT note,SUM(num) sum_num FROM books GROUP BY note ORDER BY sum_num DESC LIMIT 0,1;
# 15、 Query the title of the book to 10 A one character book , Not including the space inside
SELECT * FROM books WHERE CHAR_LENGTH(REPLACE(name,' ',''))>=10;
/* 16、 Check the title and type of the book , among note The value is novel Show novel ,law Show legal ,medicine Show medicine ,cartoon Show cartoon ,joke Show jokes */
SELECT name AS " Title " ,note, CASE note
WHEN 'novel' THEN ' A novel '
WHEN 'law' THEN ' law '
WHEN 'medicine' THEN ' medicine '
WHEN 'cartoon' THEN ' cartoon '
WHEN 'joke' THEN ' joke '
END AS " type "
FROM books;
# 17、 Check the title of the book 、 stock , among num Value exceeds 30 Ben's , Show unsalable , Greater than 0 And below 10 Of , Show best sellers , by 0 The display needs to be out of stock
SELECT name,num,CASE
WHEN num>30 THEN ' Unsalable '
WHEN num>0 AND num<10 THEN ' Sell well '
WHEN num=0 THEN ' No goods '
ELSE ' normal '
END AS " Inventory status "
FROM books;
# 18、 Count each note The stock of , And total
SELECT IFNULL(note,' Total inventory ') AS note,SUM(num) FROM books GROUP BY note WITH ROLLUP;
# 19、 Count each note The number of , And total
SELECT IFNULL(note,' Total ') AS note,COUNT(*) FROM books GROUP BY note WITH ROLLUP;
# 20、 Count the top three books in stock
SELECT * FROM books ORDER BY num DESC LIMIT 0,3;
# 21、 Find the first book published
SELECT * FROM books ORDER BY pubdate ASC LIMIT 0,1;
# 22、 find novel The most expensive book in
SELECT * FROM books WHERE note = 'novel' ORDER BY price DESC LIMIT 0,1;
# 23、 Find the book with the most words in the title , No spaces
SELECT * FROM books ORDER BY CHAR_LENGTH(REPLACE(name,' ','')) DESC LIMIT 0,1;
Copy code 边栏推荐
- In depth research and analysis report on global and Chinese p-chlorotrifluoromethane Market
- [azure application service] nodejs express + msal realizes the authentication experiment of API Application token authentication (AAD oauth2 idtoken) -- passport authenticate()
- Small open source projects based on stm32f1
- Hot seek tiger, a list of eco economic models
- Social software soul withdraws its IPO application: Tencent is a major shareholder
- 回溯法/活动安排 最大兼容活动
- 2021 年 CNCF 调查:Kubernetes 跨越鸿沟的一年
- 大道至簡 | 設計 ViT 到底怎麼配置Self-Attention才是最合理的?
- 02 Tekton Pipeline
- Seven parameters of thread pool and reject policy
猜你喜欢

High number_ Chapter 6 infinite series__ Marklaurin series

老虎国际季报图解:营收5263万美元 持续国际化布局

19. 二叉搜索树的插入删除修剪

How to manually package your own projects
![[verification of SystemVerilog] ~ test platform, hardware design description, excitation generator, monitor and comparator](/img/3a/0cc26400eeb4b388face09b9a10f27.png)
[verification of SystemVerilog] ~ test platform, hardware design description, excitation generator, monitor and comparator

数据库优化

C # - how to add and read appsetting in the console application JSON file

111. minimum depth of binary tree

Summary of some classic embedded C interview questions

Task manager based on Qt development
随机推荐
Did you break the rules?
Uniapp settings page Jump effect - navigateto switching effect - Global animationtype animation
19. insertion, deletion and pruning of binary search tree
基于STM32F1的开源小项目
China's technology goes to sea, tidb database's overseas exploration road | interview with excellent technical team
C language simple webserver
uniapp设置页面跳转效果 - navigateTo切换效果 - 全局animationType动画
思科瑞递交科创板注册:拟募资6亿 年营收2.22亿
理邦仪器软件实习生面试
如何做好自媒体?这几个步骤你做对了吗?
In depth interpretation: distributed system resilience architecture ballast openchaos
Knowledge of affairs
NVIDIA R & D director: how does AI improve chip design?
Hashicopy之nomad应用编排方案02
In the "ten billion blue ocean" database, each player can find a boat | c-position face-to-face
社交软件Soul撤回IPO申请:上市只差临门一脚 腾讯是大股东
Turning "passive" into "active", how to build security compliant intelligent products | Q recommendation
Determine whether a string contains the specified string (verified)
[process blocks and methods of SystemVerilog] ~ domain, always process block, initial process block, function, task, life cycle
In depth research and analysis report on global and Chinese content audit market