当前位置:网站首页>MySQL1
MySQL1
2022-07-24 18:53:00 【Xiaoxin has no crayons M】
Catalog
Database related concepts
database
- A warehouse for storing data , Data is organized and stored
- english :DataBase, abbreviation DB
Database management system
- Large software for managing databases
- english :DataBase Management System, abbreviation DBMS
SQL
- english : Structured Query Language, abbreviation SQL, Structured query language
- Programming language for operating relational databases
- Define a unified standard for operating all relational databases
MySQL Data model
Relational database
A relational database is a database based on a relational model , In short , Relational database is a database composed of multiple two-dimensional tables that can be connected with each other .
advantage
- They all use the table structure , The format is consistent , Easy to maintain .
- Use the universal SQL Language operation , Easy to use , Can be used for complex queries .
- Data is stored on disk , Security .
SQL
SQL brief introduction
- english : Structured Query Language, abbreviation SQL
- Structured query language , A programming language for operating relational databases
- Define a unified standard for operating all relational databases
- For the same need , There may be some differences in each way of database operation , We call it “ dialect "
SQL General grammar
- SQL Statements can be written in one or more lines , It ends with a semicolon .
- MySQL Database SQL Statement is case insensitive , It is recommended to use uppercase .
- notes · Single-line comments :-- Note content or # The comment (MySQL specific ). Multiline comment :/* notes */
SQL classification
- DDL(Data Definition Language) Data definition language , Used to define database objects : database , surface , Column, etc.
- DML(Data Manipulation Language) Data operation language , It is used to add, delete and modify the data in the database
- DQL(Data Query Language) Data query language , Used to query the records of tables in the database ( data )
- DCL(Data Control Language) Data control language , It is used to define the access rights and security level of the database , And create users

DDL—— Operating the database
1. Inquire about
SHOW DATABASES;

2. establish
- Create database
CREATE DATABASE Database name ;
- Create database ( Judge , Create... If it doesn't exist )
CREATE DATABASE IF NOT EXISTS Database name ;

3. Delete
- Delete database
DROP DATABASE Database name ;
- · Delete database ( Judge , Delete... If it exists )
DROP DATABASE IF EXISTS Database name ;
4. Using a database
- View currently used databases
SELECT DATABASE();
- Using a database
USE Database name ;
DDL -- Operation table
- establish (Create)
- Inquire about (Retrieve)
- modify (Update)
- Delete (Delete)
Query table
- Query the names of all tables in the current database SHOW TABLES;
- · Query table structure DESC The name of the table ;
Create table
- CREATE TABLE Table name (
Field name 1 data type 1,
Field name 2 data type 2,
.....
Field name n data type n
);
Be careful : At the end of the last line , No commas
data type
MySQL Support for multiple types , It can be divided into three categories :
- The number
- date
- character string


create table student( id int, name varchar(10), gender char(1), birthday date, score double(5,2), email varchar(64), tel varchar( 15), status tinyint );
Delete table
- Delete table DROP TABLE Table name ;
- When deleting a table, judge whether the table exists DROPTABLE IF EXISTS Table name ;
Modify table
1. Modify the name of the table
ALTER TABLE Table name RENAME TO New table name ;
mysql> alter table student rename stu;
Query OK, 0 rows affected (0.01 sec)⒉ Add a column
ALTER TABLE Table name ADD Column name data type ;
mysql> alter table stu add address varchar(50);
Query OK, 0 rows affected (0.05 sec)
Records: 0 Duplicates: 0 Warnings: 03. Change data type
ALTER TABLE Table name MODIFY Column name new data type ;
mysql> alter table stu modify address char(30);
Query OK, 0 rows affected (0.04 sec)
Records: 0 Duplicates: 0 Warnings: 04. Change column name and data type
ALTER TABLE Table name CHANGE Column name new column name new data type ;
mysql> alter table stu change address addr varchar(50);
Query OK, 0 rows affected (0.03 sec)
Records: 0 Duplicates: 0 Warnings: 05. Delete column
ALTER TABLE Table name DROP Name ;
mysql> alter table stu drop addr;
Query OK, 0 rows affected (0.03 sec)
Records: 0 Duplicates: 0 Warnings: 0DML
Add data
1. Add data to the specified column
INSERT INTO Table name ( Name 1, Name 2,-.)VALUES( value 1, value 2,.-);
2. Add data to all columns
INSERT INTO Table name VALUES( value 1, value 2,);
3. Batch add data
INSERT INTO Table name ( Name 1, Name 2.….)VALUES( value 1, value 2...),( value 1, value 2...),( value 1, value 2....;INSERT INTO Table name VALUES( value 1, value 2,...),( value 1, value 2...),( value 1, value 2..)..;
Modifying data
1. Modify table data
UPDATE Table name SET Name 1= value 1, Name 2= value 2,... [WHEREI Conditions ];
Be careful : If no condition is added in the modification statement , Then all data will be modified !
Delete data
1. Delete data
DELETE FROM Table name [WHERE Conditions ];
Be careful : Delete statements without conditions , Then all data will be deleted !
-- Query all the data
SELECT
*
FROM
stu;
-- Add data to the specified column INSERT INTO Table name ( Name 1, Name 2,…) VALUES( value 1, value 2,…);
INSERT INTO stu (id, NAME)
VALUES
(1, ' Zhang San ');
-- Add data to all columns , The list of column names can be omitted
INSERT INTO stu (
id, -- Number
NAME,-- full name
sex,
birthday,
score,
email,
tel,
STATUS
)
VALUES
(
2,
' Li Si ',
' male ',
'1999-11-11',
88.88,
'[email protected]',
'13888888888',
1
);
INSERT INTO stu
VALUES
(
2,
' Li Si ',
' male ',
'1999-11-11',
88.88,
'[email protected]',
'13888888888',
1
);
INSERT INTO stu
VALUES
(
2,
' Li Si ',
' male ',
'1999-11-11',
88.88,
'[email protected]',
'13888888888',
1
),(
2,
' Li Si ',
' male ',
'1999-11-11',
88.88,
'[email protected]',
'13888888888',
1
),(
2,
' Li Si ',
' male ',
'1999-11-11',
88.88,
'[email protected]',
'13888888888',
1
);
select * from stu;
-- Modifying data UPDATE Table name SET Name 1= value 1, Name 2= value 2,… [WHERE Conditions ] ;
-- Change Zhang San's gender to female
update stu set sex = ' Woman ' where name = ' Zhang San ';
-- Change Zhang San's birthday to 1999-12-12 Change the score to 99.99
update stu set birthday = '1999-12-12', score = 99.99 where name = ' Zhang San ';
-- Be careful : If update Statement not added where Conditions , All data in the table will be modified !
update stu set sex = ' Woman ';
-- Delete DELETE FROM Table name [WHERE Conditions ] ;
-- Delete three records
delete from stu where name = ' Zhang San ';
delete from stu;
DQL
- Basic query
- Conditions of the query (wHERE)
- Group query (GROUP BY)
- Sort query (ORDER BY)
- Paging query (LIMIT)
Basic query
1. Query multiple fields
SELECT Field list FROM Table name ;
SELECT * FROM Table name ; -- Query all the data
2. Remove duplicate records
SELECT DISTINCT Field list FROM Table name ;
3. names
AS: AS You can omit it
Conditions of the query
1. Conditional query syntax
SELECT Field list FROM Table name wHERE List of conditions ;
2. Conditions
Symbol function
- > Greater than
- < Less than
- >= Greater than or equal to
- <= Less than or equal to
- = be equal to
- <> or != It's not equal to
- BETWEEN ...AND ... Within a certain range ( Both contain )
- IN(...) A commonplace
- LIKE Place holder
- Fuzzy query _ Any single character % More than one arbitrary character
- IS NULL yes NULL
- IS NOT NULL No NULL
- AND or && also
- OR or || perhaps
- NOT or ! Not , No
SELECT * FROM stu;
-- Conditions of the query =====================
-- 1. Query age is greater than 20 The information of the 20-year-old student
select * from stu where age > 20;
-- 2. Query age is greater than or equal to 20 The information of the 20-year-old student
select * from stu where age >= 20;
-- 3. Query age is greater than or equal to 20 year also Age Less than or equal to 30 year Student information for
select * from stu where age >= 20 && age <= 30;
select * from stu where age >= 20 and age <= 30;
select * from stu where age BETWEEN 20 and 30;
-- 4. Check the enrollment date in '1998-09-01' To '1999-09-01' Student information between
select * from stu where hire_date BETWEEN '1998-09-01' and '1999-09-01';
-- 5. Query age = 18 The information of the 20-year-old student
select * from stu where age = 18;
-- 6. Inquiry age is not equal to 18 The information of the 20-year-old student
select * from stu where age != 18;
select * from stu where age <> 18;
-- 7. Query age = 18 year perhaps Age equals 20 year perhaps Age equals 22 The information of the 20-year-old student
select * from stu where age = 18 or age = 20 or age = 22;
select * from stu where age in (18,20 ,22);
-- 8. The English score is null Student information for
-- Be careful : null Value comparison cannot use = != . Need to use is is not
select * from stu where english = null; -- No good
select * from stu where english is null;
select * from stu where english is not null;
-- Fuzzy query like =====================
/*
wildcard :
(1)_: Represents a single arbitrary character
(2)%: Represents any number of characters
*/
-- 1. Check the last name ' Horse ' Student information for
select * from stu where name like ' Horse %';
-- 2. The second word of the query is ' flowers ' Student information for
select * from stu where name like '_ flowers %';
-- 3. The query name contains ' Virtue ' Student information for
select * from stu where name like '% Virtue %';
Sort query
1. Sort query syntax
SELECT Field list FROW Table name ORDER BY Sort field names 1[ sort order 1], Sort field names 2[ sort order 2]...;
sort order :
- ASC: Ascending order ( The default value is )
- DESC: Descending order
Be careful : If there are multiple sorting conditions , When the condition values of the current edge are the same , Will be sorted according to the second condition
/*
Sort query :
* grammar :SELECT Field list FROM Table name ORDER BY Sort field names 1 [ sort order 1], Sort field names 2 [ sort order 2] …;
* sort order :
* ASC: Ascending order ( The default value is )
* DESC: Descending order
*/
-- 1. Search for student information , In ascending order of age
select * from stu order by age ;
-- 2. Search for student information , In descending order of math scores
select * from stu order by math desc ;
-- 3. Search for student information , In descending order of math scores , If the math scores are the same , Then arrange them in ascending order of English scores
select * from stu order by math desc , english asc ;
Aggregate functions
1. Concept : Take a column of data as a whole , Do the longitudinal calculation .
2. Aggregate function classification :
Function name function
- count( Name ) Statistical quantity ( Generally, it is not null The column of )
- max( Name ) Maximum
- min( Name ) minimum value
- sum( Name ) Sum up
- avg( Name ) Average
3. Aggregate function syntax :
SELECT Aggregate function name ( Name )FROM surface ;
Be careful :null Value does not participate in all aggregate function operations
/*
Group function
SELECT Field list FROM Table name [WHERE Conditions before grouping are limited ] GROUP BY Group field name [HAVING Conditional filtering after grouping ]…;
*/
select * from stu ;
-- 1. Check the average math scores of male and female students
select sex, avg(math) from stu group by sex;
-- Be careful : After grouping , The query fields are aggregate functions and grouping fields , Querying other fields makes no sense
select name, sex, avg(math) from stu group by sex;
-- 2. Check the average math scores of male and female students , And their respective numbers
select sex, avg(math),count(*) from stu group by sex;
-- 3. Check the average math scores of male and female students , And their respective numbers , requirement : The score is below 70 Points do not participate in grouping
select sex, avg(math),count(*) from stu where math > 70 group by sex;
-- 4. Check the average math scores of male and female students , And their respective numbers , requirement : The score is below 70 Points do not participate in grouping , The number of people after grouping is greater than 2 One of the .
select sex, avg(math),count(*) from stu where math > 70 group by sex having count(*) > 2;
Paging query
1. Paging query syntax
SELECT Field list FROM Table name LIMIT Starting index , Number of query entries R
Starting index : from 0 Start
Calculation formula : Starting index =( The current page number -1)· Number of entries per page
tips :
- Paging query limit yes MySQL Dialect of database
- Oracle Paging query use rownumber
- SQL Server Paging query use top
/*
Paging query :
SELECT Field list FROM Table name LIMIT Starting index , Number of query entries
* Starting index : from 0 Start
*/
select * from stu ;
-- 1. from 0 Start searching , Inquire about 3 Data
select * from stu limit 0 , 3;
-- 2. Each page shows 3 Data , Query the first 1 Page data
select * from stu limit 0 , 3;
-- 3. Each page shows 3 Data , Query the first 2 Page data
select * from stu limit 3 , 3;
-- 4. Each page shows 3 Data , Query the first 3 Page data
select * from stu limit 6 , 3;
-- Starting index = ( The current page number - 1) * Number of entries per page
边栏推荐
- The assignment and answer of the "Cyberspace Security" competition of the 2020 secondary vocational group in Zhejiang Province (flag)
- Zip compression and decompression
- On dynamic application of binary array
- Rookie colleagues cost me 2K. Did you recite the secret of salary increase? (collect it quickly!)
- L4l7 load balancing
- Reading notes of XXL job source code
- Data model subclassing reference
- EasyUI framework dialog repeated loading problem
- Eternal Blue ms17-010exp reappears
- 04-分布式资源管理系统YARN
猜你喜欢

深度学习中Dropout原理解析

Sqoop

Typora user manual

Type-C PD protocol chip while charging and listening

Leetcode memory deep search / dynamic planning V2

OPENGL学习(四)GLUT三维图像绘制

Convolutional Neural Networks in TensorFlow quizs on Coursera

Ionic4 learning notes 3

Go小白实现一个简易的go mock server

Understand corners_ Align, two perspectives for viewing pixels
随机推荐
epoch,batch_ size
vim相关介绍
Those gods on Zhihu reply
2022 Summer Games of Hangzhou electric power multiple schools 1012aalice and Bob (game theory)
Convolution neural network receptive field calculation Guide
Go小白实现一个简易的go mock server
多线程与并发编程常见问题(未完待续)
Calling startActivity() from outside of an Activity context requires the FLAG_ ACTIVITY_ NEW_ TASK flag
Pam4 popular science
Inoic4 learning notes 2
FPGA 20 routines: 9. DDR3 memory particle initialization write and read through RS232 (Part 2)
Type-C边充边听PD协议芯片
On dynamic application of binary array
Ionic4 learning notes 9 -- an east project 01
为什么梯度是函数变化最快的方向
Common problems of multithreading and concurrent programming (to be continued)
Tclsh array operation
Some buckles
2022杭电多校第一场Dragon slayer(dfs+状态压缩)
投资的新阶段

