当前位置:网站首页>Preliminary exploration of basic knowledge of MySQL
Preliminary exploration of basic knowledge of MySQL
2022-07-05 12:33:00 【It Chunhe】
Catalog
1.4、SQL The classification of languages
2.1、DDL (Data Definition language)
2.1.1、 Operating the database (CRUD)
2.1.2、 Operation data sheet (CRUD)
One 、mysql brief introduction
Have a look first mysql Official website for mysql It's like this :mysql It's the most popular open source database in the world
1.1、 Several concepts
1、 database (database): It's organized according to the data structure 、 Warehouse for storing and managing data In short A database is a container for storing data
2、DBMS(DataBase Management System): Database management system Database software
Common database relation software :Mysql Oracle DB2 mongoDB SQLServer
3、sql: Structured query language SQL Is a standard computer language for accessing and processing databases .
MySQL Is the most popular relational database management system , stay WEB Application aspect MySQL It's the best RDBMS(Relational Database Management System: Relational database management system ) One of the application software .
1.2、mysql The advantages of
- Open source
- High performance Fast execution
- Easy to use
1.3、mysql Common commands
show databases; Query the database
use Library name ; Using a database
show tables; Query table
desc Table name ; View table structure
create table Table name ( Name Column type , Name Column type ...); Create table
1.4、SQL The classification of languages
DDL Data definition language Used to define a database surface Column, etc. create drop alter etc.
DML Data operation language Add, delete and modify the data in the table
DQL Data query language Query data in table
DCL Data control language Define the number of access permissions
Two 、 operation mysql
2.1、DDL (Data Definition language)
Database schema definition language DDL(Data Definition Language)
2.1.1、 Operating the database (CRUD)
1、C(create) Create database :
-- Create database
create database name;
-- Create a database if the database does not exist
create database if not exist name;
-- Create database and specify character set
create database name character set Character set name ;
create database zhouhao if not exists character set gbk;
2、R(Retrieve) Inquire about
show databases; -- Query all databases
shou create database name; -- Query the character set of a database & Create statement
3、U(Update) modify
-- Modify the character set of the database
ALTER DATABASE zhou CHARACTER SET gbk;
ALTER DATABASE zhou CHARACTER SET utf8;
4、D(Delete) Delete
-- Delete database
drop database name;
-- Delete if it exists
drop database if exists name;
5、 Using a database
-- Query the name of the currently used database
select database();
-- Change the database
use name;
2.1.2、 Operation data sheet (CRUD)
1、 Create table :
/*
create table tablename( Name type , Name type ...)
Database type :
int integer
double floating-point
date date Include only mm / DD / yyyy yyyy-MM-dd
datetime date Mm / DD / yyyy HHM / S yyyy-MM-dd HH:mm:ss
timestamp Time stamp Mm / DD / yyyy HHM / S If you do not assign a value to this field in the future or assign a value of null Then the current time is automatically assigned by default
varchar character string
*/
-- Create a person surface
CREATE TABLE person(
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(55),
email VARCHAR(20),
addr VARCHAR(20)
);
DESC person;
2、 Inquire about :
-- Query all the tables in the database
show tables;
-- Query table structure
desc tablename;
3、 modify :
Modify the name of the table
Modify the character set of the table
Add columns Modify the column Delete column
-- Modify the name of the table
ALTER TABLE Table name RENAME TO The new name of the table ;
-- Modify the subject character set
ALTER TABLE Table name CHARACTER SET Character set ;
-- Add a column
ALTER TABLE Table name ADD Name data type ;
-- Modify the column
ALTER TABLE Table name CHANGE Name New column names New data types ;
ALTER TABLE Table name MODIFY Name New data types
-- Delete column
ALTER TABLE Table name DROP Name ;
4、 Delete :
drop table name;
drop table name if exists;
5、 Copy table :
create table Table name 1 like The name of the copied table ;
2.2、DML
Database operation language In short, it is to operate on the data in the table (CRUD)1、 Add data
/* Adding data in the table uses insert keyword
grammar :insert into tablename ( Name 1, Name 2...) values( value 1, value 2...)
*/
-- 1、 towards person Add a piece of data to the table
INSERT INTO person (id,NAME,email,addr)VALUES(NULL,' Zhang San ','[email protected]',' hunan ');
-- 2、 Match and add data in order Only values however values The data in should match the table fields one by one
INSERT INTO person VALUES(2," Li Si ","[email protected]"," Guangzhou ");
-- 3、 Match according to column name
INSERT INTO person(NAME,addr,email) VALUES(" zhang wuji ",' sichuan ','[email protected]');
-- 4、 Add the results of the query to the table
INSERT INTO student SELECT * FROM stu;
INSERT INTO student(id,NAME,age) SELECT id,NAME,age FROM stu;
2、 Modifying data
-- Modifying data
UPDATE person SET NAME = 'zhangsan' WHERE id = 1;
-- If there is no condition Then modify all the data in the table
3、 Delete data
-- Delete data Use delete keyword
-- Basic grammar delete from Table name [where Conditions ] The conditions are optional
DELETE FROM person WHERE id=1;
-- If there is no condition Then delete all data in the table
/* There are two ways to delete all records :
1、delete from Table name ; Not recommended How many pieces of data will be deleted many times Low efficiency
2、truncate table Table name ; Delete the table first Create an identical empty table Efficient Only delete There are two operations to create a table
*/
2.3、DQL
Data query language
Inquire about keyword select
- Common query
- Query a single field
- Query multiple fields
- Query all fields
- names
- duplicate removal
- Conditions of the query
- where Conditions
- Conditional expression
- Logical expression
- Fuzzy query like Generally used with wildcards
- where Conditions
- Sort query
- order by Field asc ( Ascending ) desc( Descending )
- Aggregate functions
- count Count
- max Maximum
- min minimum value
- avg Average
- sum Sum up
- Group query
- group by Field
- Paging query limit
Sample code :
Common query
-- Query field
SELECT NAME FROM person;
-- Query multiple fields
SELECT NAME,email FROM person;
-- Query all fields
SELECT * FROM person;
-- names Use AS Or blank space To express an alias
SELECT NAME AS full name FROM person;
SELECT NAME full name FROM person;
-- duplicate removal
SELECT DISTINCT NAME AS full name FROM person;
Conditions of the query
-- Conditions of the query
SELECT NAME AS full name FROM person WHERE id = 2;
/* Conditional expression filter
> < <= >= != (<>) It's not equal to
*/
SELECT NAME AS full name FROM person WHERE id > 1;
/* Logical expression filtering
and or not
*/
SELECT NAME AS full name FROM person WHERE id > 1 AND id < 10;
SELECT NAME full name ,email AS mailbox FROM person WHERE id = 2 OR id = 3;
Fuzzy query
/* Fuzzy query
like Generally used with wildcards
betwwen and
in
is null
*/
SELECT NAME FROM person WHERE NAME LIKE '% Four %';
/* Sort query
grammar :
select Query list
from surface
[where filter ]
order by Sort list [asc( Ascending )|desc( Descending )
*/
SELECT *
FROM person
WHERE id > 2
ORDER BY id DESC;
Aggregate functions
/* Aggregate functions
1、count Calculate the number of data Generally, non empty columns are selected Primary key perhaps count(*)
2、max
3、min
4、sum
5、avg
Note that when calculating the aggregate function, the column with null The data of
Solution :
1、 Choose not null Columns of values
2、 Use ifnull function
*/
SELECT COUNT(addr) FROM person; -- 5
SELECT COUNT(NAME) FROM person; -- 8
SELECT MAX(english) AS The highest score in English FROM student;
SELECT MAX(math) AS The highest score in math FROM student;
SELECT SUM(math) FROM student;
SELECT AVG(math) FROM student;
Group query Paging query
/* Group query
group by Grouping field
*/
SELECT * FROM person GROUP BY addr;
/* Paging query
limit The starting search quote Query conditions per page
*/
SELECT * FROM person LIMIT 0,2; # first page One page shows two pieces of data
SELECT * FROM person LIMIT 2,2; # The second page
SELECT * FROM person LIMIT 4,2; # The third page
3、 ... and 、 constraint
Concept : Limit the data in the table Ensure the validity of data correctness integrity
classification : Primary key constraint Non empty constraint Unique constraint Foreign key constraints
1、 Primary key constraint
primary key
meaning : Non empty and unique
A table can only have one primary key The primary key is the unique identifier in the table
Primary key (PRIMARY KEY) The full title of the title is “ Primary key constraint ”, yes mysql The most frequently used constraint in . In general , For convenience DBMS Find records in the table faster , A primary key will be set in the table .
matters needing attention :
- Only one primary key can be defined for each table .
- The primary key value must uniquely identify each row in the table , And cannot be NULL, That is, two rows of data with the same primary key value cannot exist in the table . This is the principle of uniqueness .
- A field name can only appear once in the federated primary key field table .
- The federated primary key cannot contain unnecessary redundant fields . When a field in the union primary key is deleted , If the primary key composed of the remaining fields still satisfies the uniqueness principle , Then the joint primary key is incorrect . This is the minimization principle .
# When creating a table, specify the primary key
CREATE TABLE person (id INT PRIMARY KEY,NAME VARCHAR(20));
# Delete primary key
ALTER TABLE person DROP PRIMARY KEY;
# Add primary key
ALTER TABLE person MODIFY id INT PRIMARY KEY;
2、 Non empty constraint
not null
Indicates that the value of a specified column is non empty That is, it cannot be null
For fields with non null constraints , If the user does not specify a value when adding data , The database system will report an error . Can pass CREATE TABLE or ALTER TABLE Statements for . Add a keyword after the definition of a column in the table NOT NULL As a determiner , To constrain that the value of the column cannot be empty .
such as , In the user information table , If you don't add a user name , Then this user information is invalid , In this case, you can set a non empty constraint for the user name field .
# When creating a table, specify a non empty constraint
CREATE TABLE person (id INT,NAME VARCHAR(20) NOT NULL);
SELECT * FROM person;
# Create table Change the column to specify a non empty constraint
ALTER TABLE person MODIFY id INT NOT NULL;
# Create table Delete non empty constraints
ALTER TABLE person MODIFY id;
3、 Unique constraint
unique
The value of a column cannot be repeated Unique constraint can have null value
Unique constraint (Unique Key) It means that the values of fields in all records cannot be repeated . for example , by id After the uniqueness constraint is added to the field , For each record id Value is the only , There can be no repetition . If one of the records says id The value is ‘1’, Then there is no other record in the table id Value for ‘1’.
Unique constraints are similar to primary key constraints in that they can ensure the uniqueness of columns . The difference is , A unique constraint can have more than one in a table , And the columns with unique constraints are allowed to have null values , But there can only be one null value . The primary key constraint can only have one in a table , And no null value is allowed . such as , In the user information table , To avoid duplicate user names in the table , You can set the user name as a unique constraint .
# Specify unique constraints when creating tables
CREATE TABLE person(id INT,phonenumber VARCHAR(20) UNIQUE);
# Create table Change the column to specify a unique constraint
ALTER TABLE person MODIFY id INT UNIQUE;
# Create table Delete unique constraint The syntax of deletion is different from the above A special
ALTER TABLE person DROP INDEX id;
4、 Foreign key constraints
foreign key
mysql Of Foreign key constraints (FOREIGN KEY) Is a special field of the table , Often used with primary key constraints . For two tables that have an association , In the associated field The table where the primary key is located is the primary table ( Parent table ), The table where the foreign key is located is the slave table ( Sub table ).
Foreign keys are used to establish the relationship between the master table and the slave table , Establish a connection between the data of two tables , Constrains the consistency and integrity of data in two tables .
such as , A fruit stand , Only apples 、 Peach 、 Plum 、 Watermelon etc. 4 Kind of fruit , that , When you come to the fruit stand to buy fruit, you can only choose apples 、 Peach 、 Plum and watermelon , No other fruit can be bought .
When a record is deleted from the main table , The corresponding records from the table must be changed accordingly .
A table can have one or more foreign keys , The foreign key can be null , If not null , Then the value of each foreign key must be equal to a value of the primary key in the primary table .
# Add foreign keys when creating tables
CREATE TABLE emp(
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(20),
age INT,
dept_id INT,
CONSTRAINT emp_dept_id FOREIGN KEY (dept_id) REFERENCES dept(id)
);
SELECT * FROM emp;
#2. Delete foreign key
ALTER TABLE emp DROP FOREIGN KEY emp_dept_id;
#3. After creating the table , Add foreign keys
ALTER TABLE emp ADD CONSTRAINT emp_dept_id FOREIGN KEY (dept_id) REFERENCES dept(id);
Foreign key constraint considerations :
- The primary table must already exist in the database , Or the table that is currently being created . In the latter case , Then the master table and the slave table are the same table , Such a table is called a self reference table , This structure is called self referential integrity .
- The primary key must be defined for the primary table .
- Primary key cannot contain null value , But null values are allowed in foreign keys . in other words , As long as each non null value of the foreign key appears in the specified primary key , The content of this foreign key is correct .
- Specify the column name or combination of column names after the table name of the main table . This column or combination of columns must be the primary key or candidate key of the main table .
- The number of columns in the foreign key must be the same as the number of columns in the primary key of the primary table .
- The data type of the column in the foreign key must be the same as that of the corresponding column in the primary key of the primary table .
5、 Cascade operation
Associated foreign key Master table update The foreign key table will also be updated
# Add foreign keys to set cascading updates
ALTER TABLE emp ADD CONSTRAINT emp_dept_id
FOREIGN KEY (dept_id) REFERENCES dept(id)
ON UPDATE CASCADE -- Auto update
ON DELETE CASCADE -- Automatically delete
Cascade operation means , When you operate the main table , Automatic operation from table
边栏推荐
- Tabbar configuration at the bottom of wechat applet
- MySQL trigger
- Mmclassification training custom data
- A new WiFi option for smart home -- the application of simplewifi in wireless smart home
- ZABBIX 5.0 - LNMP environment compilation and installation
- Pytoch through datasets Imagefolder loads datasets directly from files
- Semantic segmentation experiment: UNET network /msrc2 dataset
- A guide to threaded and asynchronous UI development in the "quick start fluent Development Series tutorials"
- What is digital existence? Digital transformation starts with digital existence
- Want to ask, how to choose a securities firm? Is it safe to open an account online?
猜你喜欢
Get data from the database when using JMeter for database assertion
ABAP table lookup program
Select drop-down box realizes three-level linkage of provinces and cities in China
Anaconda creates a virtual environment and installs pytorch
嵌入式软件架构设计-消息交互
One article tells the latest and complete learning materials of flutter
[figure neural network] GNN from entry to mastery
7月华清学习-1
How can beginners learn flutter efficiently?
Read and understand the rendering mechanism and principle of flutter's three trees
随机推荐
Pytoch implements tf Functions of the gather() function
Learn the garbage collector of JVM -- a brief introduction to Shenandoah collector
Seven polymorphisms
PXE启动配置及原理
Course design of compilation principle --- formula calculator (a simple calculator with interface developed based on QT)
Principle and performance analysis of lepton lossless compression
图像超分实验:SRCNN/FSRCNN
MySQL index (1)
Just a coincidence? The mysterious technology of apple ios16 is actually the same as that of Chinese enterprises five years ago!
Matlab imoverlay function (burn binary mask into two-dimensional image)
MySQL view
Detailed structure and code of inception V3
Solution to order timeout unpaid
Learn the memory management of JVM 03 - Method area and meta space of JVM
ZABBIX agent2 monitors mongodb nodes, clusters and templates (official blog)
GNN(pytorch-geometric)
什么是数字化存在?数字化转型要先从数字化存在开始
Read and understand the rendering mechanism and principle of flutter's three trees
Want to ask, how to choose a securities firm? Is it safe to open an account online?
MVVM framework part I lifecycle