Table of contents
Create the relevant MySQL statement
Delete related MySQL statements
Modify related MySQL statements
Query related MySQL statements
Create the relevant MySQL statement
Create a database and specify the encoding format:
create DATABASE IF NOT EXISTS mydb CHARSET=utf8
Create a table (specify the primary key and encoding format of the table):
CREATE TABLE
IF NOT EXISTS `student` (
`id` INT UNSIGNED AUTO_INCREMENT,
`name` VARCHAR ( 50 ) NOT NULL,
`age` INT NOT NULL,
`sex` bit ( 2 ),
`create_time` datetime,
PRIMARY KEY ( `id` )
) ENGINE = INNODB DEFAULT CHARSET = utf8;
Insert data into all columns of the table:
INSERT INTO students VALUES (3,'xiaofang',20,1,'2022-11-29 09:46:46','1999-03-16')
Insert data into some columns of the table, and the default value is null for columns that are not inserted:
INSERT INTO students (`id`,`name`,`age`,`sex`) VALUES (1,'panshunjun',18,0)
When creating a table, specify that a column is not empty and unique:
create TABLE t_stu(
sid int PRIMARY KEY auto_increment,
`name` VARCHAR(50) not null UNIQUE);
Create a table and specify foreign keys to the table:
create table emp(
id int PRIMARY KEY auto_increment,
emp varchar(20),
deptId int,
CONSTRAINT fk_emp_dept FOREIGN KEY(deptId) REFERENCES dept(id))
Delete related MySQL statements
Drop a database:
DROP DATABASE IF EXISTS mydb
Delete a table (student is the table name):
DROP table student
delete a column in the table
alter table student drop `telphone`
Delete the contents of a table based on a condition:
delete from students where id=1
Note: delete is to delete the content of the table, the structure of the table is still there, drop is to delete the entire table
Drop the table first, then re-create the table:
TRUNCATE table t_project
delete a primary key of a table
ALTER table students drop PRIMARY key
Modify related MySQL statements
Modify the encoding format of the data (mydb is the database name, utf8 is the encoding format):
ALTER DATABASE mydb CHARACTER set utf8
Add a few columns to the table (student is the table name):
alter table student add(`birthday` date,`phone` VARCHAR(20))
Modify the type of a column in the table (student is the table name):
ALTER table student MODIFY `birthday` datetime
Change the name of a column in a table:
alter TABLE student change `phone` `telphone` varchar(22)
Modify the table name of the table:
alter table student RENAME to students
Modify the data in the table according to the conditions:
update students set age=28 where id BETWEEN 1 AND 3
update students set age=NULL where name in('panshunjun')
Modify the encoding format of the database:
set CHARACTER_set_client =utf8
Note: (CHARACTER_set_client is the format for data transmission into MySQL, and character_set_results is the format for transmission from MySQL. This modification method is only one-time. If you want to modify it once without changing it, you need to modify it in the my.ini configuration file)
Add a primary key to the created table:
ALTER table students ADD PRIMARY key(id)
Add foreign key constraints to already created tables
ALTER table emp
add CONSTRAINT fk_emp_dept FOREIGN KEY(deptId) REFERENCES dept(id)
Query related MySQL statements
View all current databases:
show databases
View all tables under the current database:
show tables
Query the creation statement of the specified table (student is the table name):
SHOW CREATE TABLE student
The structure of the query table (student is the table name):
desc student
Query all column data of the table
select * from students
Query the specified column
select name,age,sex,birthday from students
DISTINCT: Duplicate data is only displayed once (only when all are the same will they be merged into one line)
SELECT DISTINCT `name`,age,id from students
Column operations (calculation, string concatenation)
select age+1 ,CONCAT('姓名:',name) from students
IFN ULL (age,0) --If age=null, convert it to 0
select name,IFNULL(age,0)+1 from students
Alias the column ( As can be omitted )
select name,IFNULL(age,0)+1 as newAge from students
conditional query
select * from students where age>10 and `name` is not null
in method: query all the information whose names are xiaofang and zhangsan
select * from students where `name` in ('xiaofang','zhangsan')
Fuzzy query: '_' means match any one character, '%' means match any n characters
select * from students where `name` like 'panshunju_'
select * from students where `name` like 'pan%'
Sorting : Sort by age in ascending order, if the age is the same, sort by name in descending order (the default is ascending order)
select * from students ORDER BY age ASC,name desc
Query using aggregate functions:
Query the number of rows in the table:
select count(1) as '行数' number from students
Sum: Query the sum of the age column with sumAge as an alias
select sum(age) sumAge from students
Maximum value problem: query the maximum value in age
select max(age) as maxAge from students
Mean Problem: Query the mean of age
select avg(age) as avgAge from students
Comprehensive application of functions: calculate the comprehensive data of the table
select count(1) as 人数总和,sum(age) as 年龄总和,max(age) as 最大年龄,min(age) as 最小年龄,avg(age) as 年龄平均值 from students
Grouping: grouping (query the total number of men and women by gender)
select sex,count(*) from students where id>2 GROUP BY sex
Grouping condition: where condition is the condition before guiding the grouping, and the condition after HAVING guiding the grouping
select sex,count(*) from students where id>2 GROUP BY sex HAVING count(*)>1
Limit : LIMIT is used to specify how many rows to start searching, and how many pieces of data to query in total (0 means starting from a row of data)
select * from students LIMIT 0,5
View mysql database encoding:
SHOW VARIABLES LIKE 'char%'
Merge result set (union) of two tables:
//创建表ab
create table ab(a int,b varchar(10))
INSERT into ab VALUES(1,'1')
INSERT into ab VALUES(2,'2')
INSERT into ab VALUES(3,'3')
INSERT into ab VALUES(4,'4')
//创建表cd
create table cd(c int,d varchar(10))
INSERT into cd VALUES(3,'3')
INSERT into cd VALUES(4,'4')
//合并结果集查询
select * from ab UNION select * from cd
Multi-table join query--inner join:
//标准写法:
select * from emp e INNER JOIN dept d on e.deptId=d.id
Note: Inner join will find out all eligible content from the Cartesian product of the two tables, and the unqualified content will not appear in the table;
Left outer join query:
//标准写法:
select emp,deptId,IFNULL(dname,'无数据') as dname from emp as e
left join dept d
on e.deptId=d.id
Note: If the table on the left is used as the main table, the existing data in the main table will be displayed. When the main table does not have a corresponding slave table that does not meet the conditions, null will be used to replace it.
Right outer join query: (similar to left outer join query)
//标准写法
select emp,deptId,d.id ,d.dname from emp as e
right JOIN dept d
on d.id=e.deptId
Understanding of multi-table join query: For example, there are 5 pieces of data (primary) in table a and 4 pieces of data in table b. When using unconditional inner join and left and right outer join query, 20 pieces of data will be displayed. Use conditional Inner join query will display 20 eligible data, and conditional left and right outer join query will display 20 eligible data and all unconditional data in the main table will be displayed;
Backup and restore:
//Backup data script (only back up the contents of the database)
mysqldump -uroot -p123 mydb3>c:/a.sql
//Restore database script (two ways)
mysqldump -uroot -p123 mydb3<c:/a.sql
source c:/a.sql
Note: root database account 123 database password mydb3 database name c:/a.sql save address
Database permission setting
Specify a username and fixed ip for the database:
create USER [email protected] IDENTIFIED by '123456'
Specify a username and any ip for the database:
create USER admin@'%' IDENTIFIED by '123456'
Give all permissions of the ry database to the admin user under any ip
GRANT ALL ON ry.* to admin@'%'
Take back the CREATE, ALTER, and DROP permissions of the ry database admin account
REVOKE CREATE,ALTER,DROP ON ry.* FROM admin@'%'
View the permissions owned by the account under a certain ip
SHOW GRANTS for admin@'%'
Delete users under a certain ip (permission issue)
drop user admin@'%'
Note: where (GRANT ALL (all privileges) , GRANT CREATE ( create privileges) , ALTER ( modify privileges) , DROP ( delete privileges) , INSERT ( table insert privileges) , UPDATE ( table modify privileges) , DELETE ( table delete permission) , SELECT ON ( table query permission)
other statements
Database switching:
use mydb