当前位置:网站首页>MySQL foundation --- query (learn MySQL foundation in 1 day)
MySQL foundation --- query (learn MySQL foundation in 1 day)
2022-07-02 05:17:00 【Xiao Wei practiced the algorithm hard】
Catalog
2. Add data to the table (DML)
4. Operate on the data in the table (DML)
5. Table related queries (DQL)
5.4 How to judge whether it is null
5.9 DQL The order in which statements are executed
6. User permission Settings (DCL)
1. Create table (DDL)
CREATE TABLE Table name (
Field 1 Field type 【COMMENT Field 1 notes 】,
Field 2 Field type 【COMMENT Field 2 notes 】,
Field 3 Field type 【COMMENT Field 3 notes 】,
.............
Field n Field type 【COMMENT Field n notes 】
)【COMMENT Table annotation 】;
It's important to be careful here , You must not add a comma after the last field , Otherwise, it will report a mistake
Next is the creation of tables :
【 Create a emp surface , Its structure is :id(int),
name (varchar(10)),
age(int),job(varchar(20)),salary(int),
entrydate(varchar(20))
managerid(int),dept_id(int)】
CREATE TABLE emp(
id int COMMENT 'ID' PRIMARY KEY,
name VARCHAR(10) COMMENT ' full name ',
age int COMMENT ' Age ',
job VARCHAR(20) COMMENT ' Work ',
salary int COMMENT ' salary ',
entrydate VARCHAR(20) COMMENT ' date ',
managerid int COMMENT 'managerid',
dept_id int COMMENT 'dept_id'
) COMMENT ' The employee table ';
After running, you can see , There is an extra watch like this ;
2. Operate the meter (DDL)
2.1 modify
Modify the data type syntax of the table :
ALERT TABLE Table name MODIFY Field name New data types ;
【 Take the salary of the above table salary from int Type into varchar(8) type 】
alter table emp modify salary varchar(8);
After execution SQL After the statement , It can be seen that ,salary The data type of has changed .
Modify the field name and field type syntax :
ALTER TABLE Table name CHANGE Old field name new field name New field type 【COMMENT notes 】;
【 take emp In the table entrydate Change to sex(varchar(1)) And annotated with gender 】
alter table emp change entrydate sex varchar(1) comment " Gender ";
It can be seen that , Set up successfully !
Modify the syntax of the table name :
ALTER TABLE indicate RENAME The new name of the table ;
【 take emp The name of the table is changed to emp1】
alter table emp rename emp1
so , The modification was successful !
2.2 Delete
The syntax for deleting fields :
ALTER TABLE Table name DROP Field name :
【 Delete emp1 In the table salary Field 】
alter table emp drop salary;
This will be salary The field is deleted .
Delete table Syntax :
DROP TABLE [IF EXISTS] indicate ;
【 Delete emp1 surface 】
drop table if exists emp1;
emp1 The table is deleted .
Delete the specified table , And recreate the syntax of the table :
TRUNCATE TABLE Table name ;
truncate table emp;
2.3 add to
Add field Syntax
ALTER TABLE Table name ADD Field name Field type ;
【 Go to emp Add... To the table sex The type of the field is varchar(1)】
alter table emp add sex varchar(1);
To sum up :DDL Statement is to operate on the table structure .
2. Add data to the table (DML)
grammar :
INSERT INTO Table name ( Field name 1, Field name 2, Field name 3.....)VALUES ( Content 1),( Content 2).....;
Built above emp Add data to the table
INSERT INTO emp(id,name,age,job,salary,entrydate,managerid,dept_id) VALUES (1," Jin yong ",66," President ",20000,"2000-01-10",NULL,1),
(2," zhang wuji ",20," project manager ",20000,"2000-01-10",1,5),
(3," Yang Xiao ",33," Development ",20000,"2000-01-10",2,5),
(4," Xiangr ",48," Development ",20000,"2000-01-10",2,5),
(5," chang yuchun ",43," Development ",20000,"2000-01-10",2,5);
After running, you can see , Data added successfully !
4. Operate on the data in the table (DML)
4.1 to update
Syntax for updating some data in the table :
UPDATE Table name SET Field name 1= value 1, Field name 2= value 2,.....【WHERE Conditions 】
【 Raise the salary of the employee named Jin Yong to 30000】
UPDATE emp SET salary=30000 WHERE `name`=" Jin yong ";
This completes the modification .
4.2 Delete
Delete data syntax :
DELETE FROM Table name 【WHERE Conditions 】
Be careful : If you don't add conditions , All data in the table will be cleared !
【 Delete older than 45 Year old employees 】
DELETE FROM emp WHERE age>45;
According to the prompt, you can see , Older than 45 There are two people aged , And the data has been deleted .
5. Table related queries (DQL)
5.1 Alias the queried data
Add after the field list AS Or the AS Omission is also acceptable .
Be careful :"+" The role of mysql It only acts as an operation !
5.2 IF NULL Use
grammar :
IF NULL( Judge the object , If null How will );
【 Inquire about emp For everyone in the employee table salary】
It can be seen that , Wei Yixiao's salary has changed from empty to 0; In the process of adding values ,null Add to any number null, Sometimes you need to convert like this .
5.3 Conditions of the query
grammar :
SELECT Query list FROM Table name WHERE Conditions ;
Three filtering methods of conditional query :
1. Filter by conditional expression
Conditional expression operators :>,<,=,!=,<>,>=,<=;
2. Filter by logical expression
not,and,or;
3. Fuzzy query
like,between....and,in;
【 Inquire about managerid by 2 All the information about our employees 】
【 The screening age is less than 40 Or the position is the name and salary of the President 】
Wildcards are required for fuzzy queries :
% For any character ( Can match any number of )
_ Express Any character
【 The second character in the filtered employee list is _ Employee name 】
5.4 How to judge whether it is null
1. use is perhaps is not;
2. Use the safety equal sign <=>;
【 Screening manageid by null All the information of our employees 】
5.5 Aggregate functions
1.count Ask for quantity ;
2.max For maximum
3.min For the minimum
4.avg averaging
5.sum Sum up
Just show one of them here , The application is similar .
【 Query the average salary of all employees 】
It can also be seen from here ,null No participation avg The operation of a function .
5.6 Group query
grammar :
SELECT Field list name
FEOM Table name
WHERE Conditions
GROUP BY Group field name
HAVING Filter conditions after grouping
Be careful :having You can use aggregate functions
The order of execution is :WHERE > Aggregate functions > HAVING
【 Query age is greater than 45 Year old employees , And according to dept_id Grouping , Obtain more than two employees dept_id】
5.7 Sort query
grammar :
SELECT Query list FROM Table name WHERE filter ORDER BY Sort list 【ASC/DESC】
Be careful :ASC In ascending order ,DESC Arrange... In descending order ( Do not add this suffix , The default is ASC)
【 Inquire about emp All the information in the table , Rank according to age from low to high, followed by id The numbers are arranged from large to small 】
5.8 Paging query
grammar :
SELECT Query list FROM Table name LIMIT Starting index , Number of query records
Be careful :
Starting index from 0 Start , Starting index =( Query the number of pages -1)* Actual records per page
【 Check the contents of the second page , each page 3 Group data 】
5.9 DQL The order in which statements are executed
FROM List of table names
WHERE List of conditions
GROUP BY Group field list
HAVING Condition list after grouping
SELECT Field list
ORDER BY Arrange field list
LIMIT Paging parameters
Be careful :
Here is the order of execution , Instead of writing in order .
DQL The sentence ends here ,DQL It mainly queries the data in the table ;
6. User permission Settings (DCL)
6.1 User management
6.1.1 Create user
grammar :
CREATE USER ' user name '@' With that machine, you can access ' IDENTIFIED BY ' password ';
Set up the success , And successfully log in , But no permission is set for it , Later, we will talk about setting permissions ;
6.1.2 Change Password
grammar :
ALTER USER ' user name '@' With that machine, you can access ' IDENTIFIED WITH
mysql_native_password BY ' New password ';
After the modification, the original password cannot be logged on , The modified password can log in
6.1.3 Delete user
grammar :
DROP USER ' user name '@' With that machine, you can access ';
6.2 Access control :
ALL,ALL PRIVILEGES All permissions
SELSET Query data
INSERT insert data
UPDATE Modifying data
DELETE Delete data
ALTER Modify table
DROP Delete database / surface / View ;
CREAT Create database / surface
7. Common functions
7.1 String function
LENGTH Get the number of parameter value bytes
CONCAT String concatenation
UPPER Turn lowercase letters to uppercase
LOWWER Turn letters from uppercase to lowercase
SUBSTR/SUBSTRING Intercepting string , Index from 1 Start
INSERT Returns the index of the first occurrence of a string , No return found 0
TRIM Remove all characters specified before and after the substring ( Default removal “ ”)
LPAD Realize left padding with specified characters
RPAD Realize right filling with specified characters
REPLACE Replace
Try any two examples
7.2 Mathematical functions
ROUND rounding
CEIL Round up
DLOOR Rounding down
TRUNCATE truncation
RAND return 0~1 The random number
MOD modulus
【 When obtaining the verification code , Will produce a 6 Bit verification code , How is this verification code generated ?】
7.3 Date function
CURDATE Return the current system date , Not including time
CURTIME Returns the current time of the system , No date included
NOW Return current time + date
DATE_ADD(date , INTERVAL+ Time )
DATEDIFF(DATE1,DATE2) Returns the number of days of the interval
7.4 Process control functions
IF(value,t,f) If value by true, Child return t, Otherwise return to f;
IFNULL(value1,value2) If value1 Not empty , Then return to value1, Otherwise return to value2;
CASE WHEN [VAL1] THEN [RES1]....ELSE [DEFAULT] END;
If VAL1 by true, Then return to RES1........ Otherwise, return to the default DEFAULT
CASE [EXPE] WHEN [VAL1] THEN [RES1]...ELSE [DEFAULT] END;
If EXPE And VAL1 equal , Then return to RES1........ Otherwise, return to the default DEFAULT
Because it's too long , therefore mysql The foundation is divided into two phases , constraint , Operations such as multi table query will be put into the second phase ;
Study in recent days mysql Summary of , It's full of dry goods , You can collect it , Many things need to be remembered , It's easy to forget after a long time .
边栏推荐
- Mathematical knowledge -- understanding and examples of fast power
- Creation and destruction of function stack frames
- Fabric.js IText 上标和下标
- Gee series: unit 8 time series analysis in Google Earth engine [time series]
- Nodejs (03) -- custom module
- 操作符详解
- Knowledge arrangement about steam Education
- Dark horse notes -- Set Series Collection
- js面试收藏试题1
- 线程池批量处理数据
猜你喜欢
Mathematical knowledge (Euler function)
Pyechart1.19 national air quality exhibition
将光盘中的cda保存到电脑中
黑马笔记---Map集合体系
Gee series: Unit 1 Introduction to Google Earth engine
Latest: the list of universities and disciplines for the second round of "double first-class" construction was announced
C# 基于MQTTNet的服务端与客户端通信案例
运维工作的“本手、妙手、俗手”
Gee series: unit 10 creating a graphical user interface using Google Earth engine [GUI development]
Gee series: unit 9 generate sampling data in GEE [random sampling]
随机推荐
Global and Chinese market of pressure gauges 2022-2028: Research Report on technology, participants, trends, market size and share
Record my pytorch installation process and errors
Fabric.js 将本地图像上传到画布背景
LeetCode 241. Design priorities for operational expressions (divide and conquer / mnemonic recursion / dynamic programming)
C case of communication between server and client based on mqttnet
[quick view opencv] familiar with CV matrix operation with image splicing examples (3)
Fabric.js 居中元素
el-cascader回显只选中不显示的问题
Map in JS (including leetcode examples)
Gee: explore the characteristics of precipitation change in the Yellow River Basin in the past 10 years [pixel by pixel analysis]
Pyechats 1.19 generate a web version of Baidu map
Implementation of go language for deleting duplicate items in sorting array
Express logistics quick query method, set the unsigned doc No. to refresh and query automatically
fastText文本分类
指针使用详解
数据库批量插入数据
延时队列两种实现方式
Super detailed pycharm tutorial
How to make an RPM file
Basic differences between Oracle and MySQL (entry level)