当前位置:网站首页>Mysql database (II) DML data operation statements and basic DQL statements
Mysql database (II) DML data operation statements and basic DQL statements
2022-07-06 15:10:00 【Hand pluckable Xinchen】
1,DML sentence
(1) Data increase :INSERT, The main function is to add records to the database table .
(2) Data deletion :DELETE, The main function is to delete the existing records in the database table . It can be modified according to the conditions .
(3) Data modification :UPDATE, The main function is to modify the existing records in the database table . It can be modified according to the conditions .
2, Data addition :INSERT
grammar :INSERT INTO Table name [( Field 1, Field 2, Field 3... Field n)] VALUE/VALUES ( value 1, value 2, value 3... value n)[( value 1, value 2, value 3... value n)];
# DML
-- INSERT INTO Table name ( Field name , Field name , Field name )values ( value , value , value )
-- Add a student
-- Date should be represented by string
INSERT INTO student(sid,sname,birthday,ssex,classid) VALUE(9,' Zhang San ','1988-1-1',' male ',2);
-- Select a field to insert ( Data cannot be inserted if there is a default value )
INSERT INTO student(sname) VALUE(' Li Si ');
-- For full field insertion, it is not necessary to write the segment name after the table name
INSERT INTO student VALUE(11,' Wang Wu ','1999-1-1',' Woman ',1);
-- DEFAULT,NULL Default value for auto increment of primary key
-- NULL Only the primary key
INSERT INTO student(sid) VALUES(NULL);
3, Data addition :INSERT INTO SELECT
grammar :INSERT INTO table2( Field 1, Field 2...) SELECT Field 1, Field 2... FEOM table1;
-- Insert multiple pieces of data at once
-- Mode one :
-- VALUES Insert more than one VALUE Insert a
INSERT INTO student(sname) VALUES(' Li Yun '),(' Zhou Mei '),(' Wu Lan '),(' Zheng Zhu '),(' Wangju ');
INSERT INTO student VALUES(NULL,' Li Yun ','1990-08-06',' male ',2),(NULL,' Zhou Mei ','1991-12-01',' Woman ',1),(NULL,' Wu Lan ','1992-03-01',' Woman ',2),(NULL,' Zheng Zhu ','1989-07-01',' Woman ',1),(NULL,' Wangju ','1990-01-20',' Woman ',2);
-- Mode two :
-- INSERT INTO SELECT
-- Tables exist
CREATE TABLE newstu(
xingming VARCHAR(10),
xingbie VARCHAR(10)
);
INSERT INTO newstu(xingming,xingbie) SELECT sname,ssex FROM student;
-- Mode three :
-- CREATE TABLE New table SELECT;
CREATE TABLE stu SELECT sid,sname,birthday FROM student;
SHOW CREATE TABLE stu;
4, Data modification :UPDATE
grammar :UPDATE Table name SET Field 1 = value 1 [SET Field 2 = value ...] [WHERE Conditions ]
# modify
-- WHERE Must write
-- UPDATE Table name SET Field name = value , Field name = value ... Field name = value [WHERE Clause ]
UPDATE newstu SET xingbie=' male ' WHERE xingming=' Qian Dian ';
UPDATE stu SET birthday='2022-06-07' WHERE sid <> 3;
UPDATE stu SET birthday='2000-01-01' WHERE sid >= 4 AND sid <=8;
UPDATE stu SET birthday='1888-01-01' WHERE sid BETWEEN 4 AND 8;
5,WHERE Clause
Operator | meaning | give an example | result |
---|---|---|---|
= | be equal to | 5 = 6 | false |
< > or ! = | It's not equal to | 5 != 6 | true |
> | Greater than | 5 > 6 | false |
< | Less than | 5 < 6 | true |
>= | Greater than or equal to | 5 >= 6 | false |
<= | Less than or equal to | 5 <= 6 | true |
BETWEEN | In a certain range | BETWEEN 5 AND 10 | - |
AND | also | 5 > 1 AND 1 > 2 | false |
OR | or | 5 > 1 OR 1 > 2 | true |
NOT | Not |
=:set The latter represents assignment ,where Said judgment
6, Data deletion :DELETE
grammar :DELETE FROM Table name [WHERE Conditions ];
# Delete
-- DELETE FROM Table name [WHERE Clause ]
-- All data in the table is deleted
DELETE FROM newstu;
DELETE FROM stu WHERE sname=' Zhao Lei ';
DELETE FROM stu WHERE sid >=2 AND sid <= 6;
-- BETWEEN Followed by small data AND Followed by big data
DELETE FROM stu WHERE sid BETWEEN 7 AND 10;
7, Data clearing :TRUNCATE
TRUNCATE [TABLE] Table name ;
-- Clear the table
-- TRUNCATE Table name
TRUNCATE stu;
DELETE FROM student;
TRUNCATE student;
-- DELETE TRUNCATE difference
-- DELETE Do not delete index values
8,MySQL Database recovery method
Console recovery :mmysql –h localhost -P 3306 –u root –p day001 < /path/db_name.sql;
day001 : Name of the database to recover .
/path/db_name.sql : To recover the absolute path of the database .
Console backup :mysqldump -h localhost –P 3306 –u root –p day001 > /path/db_name.sql;
day001 : Name of the database to be backed up .
/path/db_name.sql : The absolute path of the database to be backed up .
9, The role and value of database backup and recovery
High availability : Minimize the number of database failures , So as to maintain the maximum availability of the database .
Security : Computer virus 、 Trojan horse type 、“ hackers ” Invasive 、 Logic bomb type will cause information loss , Lost data needs to be recovered in time .
integrity : When the database fails , Ensure that as little or no data is lost , So that the data has the greatest integrity .
10, Single table query
select [distinct]
{ * or surface 1.* or [ surface 1. Field 1 [ as Field alias 1] [, surface 1. Field 2 [as Field alias 2]] [......] ] }
from surface 1 [as Table alias ]
[left or rigth or inner join surface 2 on The relationship between tables ]
[where]
[group by]
[limit {[ Position offset ,] Row number }];
keyword | effect |
---|---|
distinct | Remove duplicate records in the table |
as | Alias the field name or table name |
group by | Display the queried data by group classification |
having | Play the role of conditional restriction after grouping |
order by | Sort the queried data |
limit | Limit the number of results displayed |
# Inquire about
-- The simplest query
SELECT 'abc';
-- Query from a data table
-- Full field query
-- SELECT Field name ..., Field name FROM Table name ;
-- recommend
SELECT sid,sname,birthday,ssex,classid FROM student;
-- Not recommended , Do not conform to the sql Optimization principle
SELECT * FROM student;
-- Partial field query
SELECT sname,ssex,' Ape academy ' FROM student;
-- Alias fields
SELECT sname AS ' full name ',ssex ' Gender ',' Ape academy ' School FROM student;
11, Remove duplicate data :distinct
grammar :select distinct Field name 1, Field name 2... from Table name
effect : Get rid of select Duplicate records in the returned record result of query ( All return columns have the same value ), Just return one .
-- DISTINCT Remove duplication ( Query all fields the same , Remove the repetitive ones )
SELECT DISTINCT sname,birthday FROM student;
12,where
grammar :select * from Table name [where Conditions ];
-- Conditional query
SELECT * FROM student WHERE ssex = ' male ';
SELECT * FROM student WHERE ssex = ' male ' AND classid = 2;
SELECT * FROM student WHERE ssex = ' Woman ' AND classid != 2;
-- sid(4-7)
SELECT * FROM student WHERE sid BETWEEN 4 AND 7;
SELECT * FROM student WHERE sid >= 4 AND Sid <= 7;
-- sid !(4-7)
SELECT * FROM student WHERE sid <= 4 OR sid >= 7;
-- Find a birthday greater than 1990 Of the students ( Dated )
SELECT * FROM student WHERE birthday < '1990-1-1';
INSERT INTO student (sname) VALUES (' Teacher wang '),(' Teacher Wang next door '),(' Handsome teacher Wang '),(' Lao Wang '),(' Wang Yanyi ');
13,like Fuzzy query
grammar :select * from Table name where Field like Conditions ;
-- LIKE Fuzzy query
-- Fuzzy symbols
-- % Any number of any characters
-- _ An arbitrary character
SELECT * FROM student WHERE Sname LIKE ' king %';
SELECT * FROM student WHERE Sname LIKE '% king %';
SELECT * FROM student WHERE sname LIKE ' king _';
14,in Range queries
grammar :select * from Table name where Field in ( value 1, value 2, value 3...);
-- IN In this range
-- 2,4,5,7,9,200
SELECT * FROM student WHERE Sid IN (2,4,5,7,9,200);
15,null
grammar :select * from Table name where Field is null or is not null;
-- Yes null Conditions
SELECT * FROM student WHERE birthday is NULL;
SELECT * FROM student WHERE birthday is NOT NULL;
16, Aggregate functions
Function name | Return value |
---|---|
avg(col) | Returns the average value of the specified column |
count(col) | Returns the value of the specified column null The number of values |
min(col) | Returns the minimum value of the specified column |
max(col) | Returns the maximum value of the specified column |
sum(col) | Returns the sum of all specified columns |
-- Aggregate functions
-- COUNT( Field name ) Number of Statistics
-- COUNT No statistics null
-- It is recommended to use the primary key to count the number
-- * recommend
-- Constant recommend
-- Count out how many male students there are in the student list
SELECT COUNT(Ssex) FROM student WHERE Ssex= ' male ';
-- Are all statistical
-- AVG( Field name ) averaging
SELECT AVG(score) FROM sc;
-- MAX( Field name ) Maximum
SELECT MAX(score) FROM sc;
-- MIN( Field name ) minimum value
SELECT MIN(score) FROM sc;
-- SUM( Field name ) The sum of the
SELECT SUM(score) FROM sc;
-- Count the total number of exams in the transcript , The highest , Lowest score , average , Total score
SELECT COUNT(*) frequency ,MAX(score) The highest ,MIN(score) Lowest score ,AVG(score) average ,SUM(score) Total score FROM sc;
17,group by and having grouping
group by:
1、 Group all data .
2、 There can be multiple fields for grouping , And group them in turn .
having:
And group by Use a combination of , Data filtering after grouping
-- grouping GROUP BY
-- Count the number of different genders in the student table
SELECT ssex,COUNT(1) FROM student GROUP BY Ssex;
-- Count the number of different classes in the student table
SELECT classid class , COUNT(*) FROM student GROUP BY classid;
-- The average score of each student in the transcript
SELECT sid,AVG(score) FROM sc GROUP BY Sid;
-- Statistics results Each student is greater than 60 Total score of points
SELECT sid,SUM(score) FROM sc WHERE score >=60 GROUP BY Sid;
-- Filter after grouping HAVING
-- The total score is greater than 200 branch
-- WHERE There can be no aggregated data behind
-- HAVING The latter condition is the screening after aggregation
-- Not alone , It has to be with GROUP BY Come together
-- WHERE and HAVING The difference between
SELECT sid,SUM(score) FROM sc WHERE score >= 60 GROUP BY Sid HAVING SUM(score) > 200;
-- Find the average score of each course , It shows that the average score is greater than 85 Courses with scores and average scores
SELECT cid,AVG(score) FROM sc GROUP BY cid HAVING AVG(score) >85;
18,order by Sort
grammar :select * from Table name order by Field name [desc or asc];
-- Sort
-- DESC Descending
-- ASC Ascending
-- The rules : Write first, arrange first , Write back
SELECT * FROM student ORDER BY Sid;
SELECT * FROM sc ORDER BY score DESC,Cid DESC;
19,limit Pagination
grammar :selsct * from Table name limit [n,m];
-- LIMIT Pagination
-- LIMIT num The first few
-- LIMIT num( Location ),num( step )
SELECT * FROM student LIMIT 0,3;
-- The formula :( Page number -1)* step
-- Wrong writing
SELECT * FROM student LIMIT (1-1)*3,3;
-- Find out the students whose average score in the exam is the second in the score table
SELECT sid,AVG(score) FROM sc GROUP BY sid ORDER BY AVG(score) DESC LIMIT 1,1;
边栏推荐
- Pointer -- eliminate all numbers in the string
- Programmers, how to avoid invalid meetings?
- Which version of MySQL does php7 work best with?
- MySQL数据库(二)DML数据操作语句和基本的DQL语句
- Differences between select, poll and epoll in i/o multiplexing
- Introduction to variable parameters
- Pedestrian re identification (Reid) - Overview
- [pointer] solve the last person left
- 全网最详细的postman接口测试教程,一篇文章满足你
- Global and Chinese market of maleic acid modified rosin esters 2022-2028: Research Report on technology, participants, trends, market size and share
猜你喜欢
软件测试方法有哪些?带你看点不一样的东西
CSAPP Shell Lab 实验报告
Capitalize the title of leetcode simple question
王爽汇编语言学习详细笔记一:基础知识
Install and run tensorflow object detection API video object recognition system of Google open source
Want to learn how to get started and learn software testing? I'll give you a good chat today
MySQL数据库(四)事务和函数
Fundamentals of digital circuits (II) logic algebra
Cc36 different subsequences
STC-B学习板蜂鸣器播放音乐
随机推荐
C language learning summary (I) (under update)
自动化测试你必须要弄懂的问题,精品总结
Maximum nesting depth of parentheses in leetcode simple questions
软件测试需求分析之什么是“试纸测试”
Fundamentals of digital circuits (II) logic algebra
Servlet
Why can swing implement a form program by inheriting the JFrame class?
About the garbled code problem of superstar script
Four methods of exchanging the values of a and B
Zhejiang University Edition "C language programming experiment and exercise guide (3rd Edition)" topic set
[HCIA continuous update] advanced features of routing
UCORE lab7 synchronous mutual exclusion experiment report
Pointer -- output all characters in the string in reverse order
Description of Vos storage space, bandwidth occupation and PPS requirements
Es full text index
[pointer] find the value of the largest element in the two-dimensional array
MySQL数据库(一)
接口测试面试题及参考答案,轻松拿捏面试官
CSAPP家庭作業答案7 8 9章
Oracle foundation and system table