MySQL database technology
6. DCL (Data Control Language) operation management user and authorization
DBA data administrator
1. Manage users
1) Add users
Syntax: create user username@'hostname IP address' identified by'password';
-- 创建用户,用户只能在指定IP 地址上登录
create user magic@'192.168.1.113' identified by'';
--用户可以在任意IP地址下登录
create user magic@'%' identified by'';
2) Query the user, the data table under mysql
select * from user;
select host,user from user;
3) Delete user
drop user username@'hostname IP address'
4) Modify user password
After 5.7, the password field is changed to authentication_string
①update user set password = password('new password') where user ='user name';
②set password for username@'hostname IP address' = password('new password')
5) Refresh authority instruction
flush privileges;
6) Forgot password
[External link image transfer failed. The source site may have an anti-hotlinking mechanism. It is recommended to save the image and upload it directly (img-sNxks4H1-1608272878707) (C:\Users\24582\AppData\Roaming\Typora\typora-user-images\ image-20201215150408764.png)]
2. Authorization management
At this point, the user can connect to the mysql database, but can only use very few permissions, so other users are required to give it permissions
1) Query permissions
show grants for username@'hostname IP address'
2) Grant permissions
Grant permission list on database name. Table name to user name@'host name IP address'
-Assign multiple permissions to users
eg:grant select,update,insert create on mydb1.student to magic@’%’;
-Grant all permissions to the magic user, perform various operations on any table in any database, the permissions are equivalent to the root user
grant all on*.* to'username'@'hostname';
3) Revocation of authority
revoke permission list on database name. table name from user name@'host name';
-Revoke all permissions of the user
revoke all on database name.* from username@'hostname';
7. Graphical database management tool: SQLYog client management tool
1. Concept:
SQLyog is a fast and simple graphical management tool for MYSQL database. It can effectively manage your database at any location. It is produced by the well-known Webyog company in the industry.
2. Installation:
Just install it on Baidu
8. DQL query statement
1. Simple query:
The query will not modify the data in the database, has no effect, but is just a way to display the data
grammar:
-- select 字段列表 from 表名列表;
-- select 字段列表 from 表名列表 where 条件;
desc student;-- 查询student表结构
select sname,age from student; -- 查询指定字段,名字年龄
select * from student; -- 查询表的所有列
-- 查询中出现重复,则删除重复 distinct
select distinct address from student; -- 去掉重复信息
-- 起别名 as 也可以省略,表上也可以使用
select name as 姓名,age AS 年龄 from student;
-- 计算列 加减乘除
-- eg:所有年龄加5
select age+5 from student;
2. Condition query:
> < >= <= = != <>
and 或 &&: SQL中建议使用前者,
or 或 ||
not 或 !
between... and...:在一定范围内
in(多个值): 表示多个数据,使用逗号分隔
like: 模糊查询
点位符:_:单个任意字符
%:多个任意字符
is null:空值
-- 查询年龄大于19的
SELECT * FROM student WHERE age>=19;
-- 查询年龄大于18,小于20的
SELECT * FROM student WHERE age>18 AND age<20;
-- 查询年龄一定范围内
SELECT * FROM student WHERE age BETWEEN 18 AND 20;
-- 满足其中一个就可以
SELECT * FROM student WHERE age IN(18,19);
-- 查询姓名中带o的同学
SELECT * FROM student WHERE sname LIKE '%o%';
3. Sort query:
语法:
order by 排序字段1 排序方式1... -- 多个字段进行排序
asc:升序
desc:降序
-- 查询记录时,按照年龄升序输出
SELECT * FROM student ORDER BY age ASC;
-- 查询记录时,按照年龄降序输出
SELECT * FROM student ORDER BY age DESC;
-- 按照年龄升序排序,若年龄相同,按照id降序排列
SELECT * FROM student ORDER BY age ASC,id DESC;
4. Aggregate functions:
Take a column of data as a whole for vertical calculation
count():计算个数
max():计算最大值
min():计算最小值
sum():计算和
avg():计算平均分
-- 查询学生总数,null不会被统计
SELECT COUNT(id) FROM student;
SELECT COUNT(*) FROM student;-- 表示只有一列数据有一个不为null值,就算一行记录(常用*)
-- 查询计算年龄最大值、最小值
SELECT MAX(age) FROM student;
SELECT MIN(age) FROM student;
-- 查询年龄总和
SELECT SUM(age) FROM student;
--查询年龄的平均年龄
SELECT AVG(age) FROM student;
5. Group query
-- 按照性别查询,按照男女分别多少人?
语法:
group by -- 用于对查询的结果进行分组
having -- 子句,用于限制分组显示结果,对结果再次筛选
SELECT sex,COUNT(*) FROM student GROUP BY sex;
-- 按照性别查询,按照男女分别多少人,且平均年龄?
SELECT sex,COUNT(*),AVG(age) FROM student GROUP BY sex;
-- 按照性别查询,按照男女分别多少人,且平均年龄,年龄低于18的不参加分组?
SELECT sex,COUNT(*),AVG(age) FROM student WHERE age>18 GROUP BY sex;
--where和having区别?
①where在分组之前进行限定,如果不满足条件,则不参与分组
having在分组之后进行限定,如果不满足条件,不会被查询出来
②where后不可以跟聚合函数
having后可以
Nine, the constraints of the data table
1. Concept:
It is to limit the data in the table to ensure the correctness, validity and completeness of the data
If a table has constraints added, incorrect data cannot be added
2. Classification:
Primary key constraint: primary key
Non-empty constraint: not null
The only constraint: unique
Foreign key constraint: foreign key
3. Primary key constraint: primary key
-- 用来唯一标识数据库中的每一条记录,当定义了主键约束后,该列不但不能重复而且不能为null
--创建表时,添加主键约束
CREATE TABLE stu(
id INT PRIMARY KEY,-- 定义列时指定主键
sname VARCHAR(50)
)
CREATE TABLE stu(
id INT,
sname VARCHAR(50),
PRIMARY KEY(id) --定义完所有列后添加主键
)
-- 删除主键的方法
ALTER TABLE stu DROP PRIMARY KEY;
--创建完成后,添加主键
ALTER TABLE stu ADD PRIMARY KEY(id);
-- 注意:
主键的含义是非空且唯一
一张表只能有一个字段为主键
主键就是表中记录的唯一标识
--插入重复的值
INSERT INTO stu(id,sname) VALUES(1,'tom');
INSERT INTO stu(id,sname) VALUES(1,'tom');
错误代码: 1062
Duplicate entry '1' for key 'PRIMARY'
--插入空值
INSERT INTO stu(id,sname) VALUES(NULL,'tom');
错误代码: 1048
Column 'id' cannot be null
Automatic growth
Keyword: auto_increment
When creating the table, add primary key constraints and complete the growth of the primary key
CREATE TABLE stu3(
id INT PRIMARY KEY AUTO_INCREMENT,-- 给id添加主键约束,设置为自动增长
sname VARCHAR(50)
)
-- 删除自动增长
ALTER TABLE stu3 MODIFY id INT;
-- 创建表之后,再添加自动增长
ALTER TABLE stu3 MODIFY id INT AUTO_INCREMENT;
-- 使用
INSERT INTO stu3(sname) VALUES ('tom');
INSERT INTO stu3(id,sname) VALUES(NULL,'rose');
-- 修改主键自增从200开始
ALTER TABLE stu3 AUTO_INCREMENT=200;
delete:删除删除所有的记录之后,自增长没有影响,从200--201
truncate:删除之后,自增长从0开始
4. Non-empty constraint: not null
concept
A column of the data table cannot be null. If not null is defined on the column, when inserting data, you must provide data for the column. It is meaningless to be empty
format
-- 创建表时添加约束
create table stu(
id int,
sname varchar(20) not null -- 创建了非空约束
)
-- 创建表结束后,添加非空约束
alter table 表名 modify sname varchar(20) not null;
-- 删除字段的非空约束
alter table 表名 modify sname varchar(20);
-- 案例
INSERT INTO stu3 VALUES(1,NULL);
-- 错误代码: 1048
Column 'sname' cannot be null
5. Default value: set a default value for a field
grammar
create table stu(
id int primary key,
sname varchar(20) not null,
sex varchar(10) default 'man' -- 默认为男
)
INSERT INTO stu2(id,sname,sex)VALUES(1,'zjd','woman');
INSERT INTO stu2(id,sname,sex)VALUES(2,'txw',NULL);
INSERT INTO stu2(id,sname,sex)VALUES(3,'txb',DEFAULT);
6. Unique constraint: unique
concept
A column in the data table cannot have duplicate values, and uniqueness must be guaranteed. When a column of data defines a unique constraint, it cannot be repeated
grammar
-- 创建表示添加唯一约束
CREATE TABLE stu(
id INT PRIMARY KEY,
sname VARCHAR(20) UNIQUE
)
-- 创建之后添加唯一约束
alter table 表名 modify 字段名 字段类型 unique
ALTER TABLE stu MODIFY sname VARCHAR(20) UNIQUE;
-- 删除字段的唯一约束
ALTER TABLE stu DROP INDEX sname;
--案例
INSERT INTO stu(id,sname) VALUES(1,'tom');
INSERT INTO stu(id,sname) VALUES(2,'tom');
-- 错误代码: 1062
Duplicate entry 'tom' for key 'sname'
-- 注意:
当插入的数据都为null值,则可以重复
INSERT INTO stu(id,sname)VALUES(3,NULL);
INSERT INTO stu(id,sname) VALUES(4,NULL);
mysql数据库中,唯一约束限定的列的值可以有多个null值
[External link image transfer failed. The source site may have an anti-hotlinking mechanism. It is recommended to save the image and upload it directly (img-VPG40bjc-1608272878709) (C:\Users\24582\AppData\Roaming\Typora\typora-user-images\ image-20201217145207964.png)]
Expand
If a field is set with a unique constraint, what is the difference between the field and the primary key?
Primary key : a table can only have at most one primary key, not null plus self-growth
Unique : a table can have multiple unique constraints, can have multiple nulls, cannot add self-growth
7. Foreign key constraints: foreign key
Preface
Disadvantages when storing data in a single table:
① Duplicate data and redundant data
②There are problems when adding, deleting and modifying later
Solution:
Split table, split into multiple tables
CREATE TABLE class(-- 主表
cno INT PRIMARY KEY AUTO_INCREMENT, -- 班级编号
cname VARCHAR(50), -- 班级名称
address INT -- 班级对应教室号
)
CREATE TABLE student(-- 从表
id INT PRIMARY KEY AUTO_INCREMENT, -- 学生编号
sname VARCHAR(50), -- 姓名
age INT, -- 年龄
cno INT -- 班级
)
-- 添加两个班级
INSERT INTO class VALUES(1,'classone',101),(2,'classtwo',102);
-- 添加学生
INSERT INTO student(id,sname,age,cno) VALUES(1801,'tom',18,1);
INSERT INTO student(id,sname,age,cno) VALUES(1802,'Jack',19,1);
INSERT INTO student(id,sname,age,cno) VALUES(1803,'rose',18,1);
INSERT INTO student(id,sname,age,cno) VALUES(1804,'bib',19,2);
INSERT INTO student(id,sname,age,cno) VALUES(1805,'lily',18,2);
INSERT INTO student(id,sname,age,cno) VALUES(1806,'cir',19,2);
Foreign key constraint concept
Used to define the relationship between the primary table and the secondary table, foreign key constraints must be defined on the secondary table, the primary table must have primary key constraints, so as to ensure the correctness and validity of the data
Main table: one side, the table used to constrain others
From the table: many parties, a table bound by others
grammar
create table 表名(
列名 数据类型,
……
外键列
constraint 外键名称 foreign key(外键列名称) references 主表名称(主表列名称)
)
CREATE TABLE student(
id INT PRIMARY KEY AUTO_INCREMENT, -- 学生编号
sname VARCHAR(50), -- 姓名
age INT, -- 年龄
cno INT, -- 班级
CONSTRAINT student_fk FOREIGN KEY(cno) REFERENCES class(cno)
)
-- 删除外键
alter table 表名 drop foreign key 外键名称;
ALTER TABLE student DROP FOREIGN KEY student_fk;
-- 创建表之后添加外键
alter table 表名 add
constraint 外键名称 foreign key(外键列名称) references 主表名称(主表列名称)
ALTER TABLE student ADD
CONSTRAINT student_fk FOREIGN KEY(cno) REFERENCES class(cno);
--案例:插入不存在的班级报错
错误代码: 1452
Cannot add or update a child row: a foreign key constraint fails (`mystudy`.`student`, CONSTRAINT `student_fk` FOREIGN KEY (`cno`) REFERENCES `class` (`cno`))
Other constrained tables
grammar
create table 表名(
列名 数据类型,
……
外键列
constraint 外键名称 foreign key(外键列名称) references 主表名称(主表列名称)
)
CREATE TABLE student(
id INT PRIMARY KEY AUTO_INCREMENT, -- 学生编号
sname VARCHAR(50), -- 姓名
age INT, -- 年龄
cno INT, -- 班级
CONSTRAINT student_fk FOREIGN KEY(cno) REFERENCES class(cno)
)
-- 删除外键
alter table 表名 drop foreign key 外键名称;
ALTER TABLE student DROP FOREIGN KEY student_fk;
-- 创建表之后添加外键
alter table 表名 add
constraint 外键名称 foreign key(外键列名称) references 主表名称(主表列名称)
ALTER TABLE student ADD
CONSTRAINT student_fk FOREIGN KEY(cno) REFERENCES class(cno);
--案例:插入不存在的班级报错
错误代码: 1452
Cannot add or update a child row: a foreign key constraint fails (`mystudy`.`student`, CONSTRAINT `student_fk` FOREIGN KEY (`cno`) REFERENCES `class` (`cno`))