Three, MySQL data management
3.1 foreign key
Add a foreign key constraint when creating tables
CREATE TABLE `student` (
`id` int(20) NOT NULL AUTO_INCREMENT COMMENT '学号',
`name` varchar(30) NOT NULL DEFAULT '匿名' COMMENT '姓名',
`password` varchar(20) NOT NULL DEFAULT '123456' COMMENT '密码',
`sex` varchar(2) NOT NULL DEFAULT '女' COMMENT '性别',
`birthday` datetime DEFAULT NULL COMMENT '出生日期',
`gradeid` int(10) NOT NULL COMMENT '学生的年级',
`address` varchar(100) DEFAULT NULL COMMENT '家庭住址',
`email` varchar(20) DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (`id`),
FOREIGN KEY (`gradeid`) REFERENCES `grade`(`gradeid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
CREATE TABLE `grade` (
`gradeid` int(10) NOT NULL AUTO_INCREMENT COMMENT '年级id',
`gradename` varchar(50) NOT NULL COMMENT '年级名称',
PRIMARY KEY (`gradeid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
Physical foreign keys is not recommended! (To avoid problems caused by excessive database)
Best Practices:
- The database is a simple table, just to keep the data, only the row (data) and columns (fields)
- We want to use data from multiple tables, and want to use the foreign key (program to achieve)
Language 3.2 DML (Data Manipulation Language)
Meaning the database:
Data storage, data management
- Insert
- update
- delete
Add 3.3
insert
-- 插入语句(添加)
-- insert into 表名([字段1,字段2,字段3]) values ('值1'),('值2'),('值3');
insert into `grade` (`gradename`) values ('大四');
-- 由于主键自增,我们可以省略 (如果不写表的字段,他就会--匹配)
-- 一般写插入语句,要将数据与字段一一对应
-- 插入多个字段
insert into `grade` (`gradename`) values ('大三'),('大二'),('大一');
Syntax: insert into table ([field name 1, 2 field names, field names 3]) values ( 'value 1'), ( 'value 2'), ( 'value 3');
Precautions:
- Use between fields and fields separated by commas
- Field may be omitted, the following values must correspond
- A plurality of data can be inserted at the same time, the value of the latter values, need, separated
3.4 Modify
update
-- 修改语句
update `grade` set `gradename` = '大一' where gradeid = 1;
-- 不指定条件的情况下,会改动所有
update `grade` set `gradename` = '初始';
-- 修改多个条件
update `grade` set `gradename` = '大四', `gradep` = 12 where gradeid = 1;
Syntax:. Update table set colnum_name = value [colnum_name = value] where [condition]
Conditions: where clause operator id is equal to a value greater than a value, modified in a certain interval ....
Operator returns a Boolean value
Operators | meaning | range | result |
---|---|---|---|
= | equal | 5 = 6 | false |
<> Or! = | not equal to | 5 <> 6 | true |
> | |||
< | |||
<= | |||
>= | |||
BETWEEN ... and ... | In a range | [2,5] | |
AND | && | 5 > 1 and 1 > 2 | false |
OR | || |
-- 通过多个定位条件定位数据
update `grade` set `name` = '长江7号' where `name` = '磊' and sex = '男'
note:
- colnum_name is a column of the database, possible wear ``
- Conditions, screening conditions, if not specified, all columns modifications
- value, which is a specific value
update `student` set `brithday` = CURRENT_TIME `name` = '长江7号' AND sex = '男'
3.5 Delete
delete command
Syntax: delete from table [where conditions]
-- 删除数据
delete from `grade`;
-- 删除指定数据
delete from `grade` where gradeid = 1;
TRUNCATE command
Role: a completely empty database tables, indexes and constraints table structure will not change!
-- 清空 student 表
truncate `student`
delete and TRUNCATE difference
The same point: can delete data, table structure will not be deleted
- different:
- TRUNCATE will reset the auto-increment counter to zero
- TRUNCATE will not affect the transaction
-- 测试delete 和 TRUNCATE区别
create table `test` (
`id` int(4) not null auto_increment,
`coll` varchar(20) not null,
primary key (`id`)
)ENGINE = InnoDB Default charset = utf8;
insert into `test` (`coll`) values ('1'),('2'),('3');
delete from test; -- 不会影响自增
insert into `test` (`coll`) values ('1'),('2'),('3');
TRUNCATE table `test`; -- 自增归零
insert into `test` (`coll`) values ('1'),('2'),('3');
DELETE Delete the problem: Restart the database phenomenon
- InnoDB auto increment will start at 1 (in memory of them, power that is lost)
- MyISAM continue on a self-increment from the beginning (the file exists, will not be lost)
Four, DQL query data
4.1 DQL
(Data Query Language: Data Query Language)
- All queries are with him Select
- Simple queries, complex queries he can do -
- The core of the database language
- Most frequently used
4.2 Queries all fields
-- 查询所有
select * from student;
-- 查询指定字段
select `name`,`sex` from student;
-- 别名,给结果起一个名字 AS 可以给字段起别名
select `name` as 姓名, `sex` from student;
-- 函数 Concat (a,b)
select concat('姓名: ', name) from student;
Column names can play an alias AS
Deduplication disinct
Role: to remove out of the SELECT query results in duplicate data and displays a
select distinct `gradeid` from student;
Column database
-- 查询系统的版本(函数)
select VERSION();
-- 用来计算(表达式)
select 100 * 3 - 1 as how;
-- 查询自增的步长(变量)
select @@auto_increment_increment;
-- 学生的密码 +1 查看
select `name`,`password`+1 as `密码+1后`from student;
Expression database: text value column, Null, function calculation expression system variables ....
select expression from table
4.3 where conditional clause
Action: retrieve data values meet the conditions
Logical Operators
Conditions search by one or more expressions! Result of a Boolean value
Operators | grammar | description |
---|---|---|
and && | a and b a && b | Logic and both are true, the result is true |
or || | a or b a || b | Or logic, which is true, the result is true |
Not ! | not a ! a | Non-logic, true false false true! |
-- ============================ where =================================
select `name`, `password` from student;
-- 查询学生密码在10000以上的学生
select `name`, `password` from student where password > 10000;
-- and && 查询学生密码在1000以上,10000以下的学生
select `name`, `password` from student where password > 1000 && password < 10000;
-- 模糊查询(区间) between and
select `name`, `password` from student where password between 1000 and 10000;
-- 除了1234密码的学生 ! not
select `name`, `password` from student where password != 1234;
select `name`, `password` from student where not password = 1234;
Fuzzy query: Comparison operators
Operators | grammar | description |
---|---|---|
IS NULL | a is null | If the operator is NULL, the result is true |
IS NOT NULL | a is not null | If the operator is not NULL, the result is true |
BETWEEN | a between b and c | If a between b and c, the result is true |
LIKE | a like b | SQL match, if a match b, then the result is true |
IN | a in (a1,a2,a3...) | In a hypothesis a1, ... or A2 |
-- =============================== 模糊查询 ====================================
-- 查询姓张的同学
-- like结合 %(代表0到任意个字符) _(一个字符)
select `id`,`name` from student where name like '张%';
-- 查询姓张,后面只有一个字的
select `id`,`name` from student where name like '张_';
-- 查询名字中有烁的同学
select `id`,`name` from student where name like '%烁%';
-- ====================== in(具体的一个或者多个值) ===========================
-- 查询 1,2,3号学生
select `id`,`name` from student where id in (1,2,3);
-- 查询地址在呼和浩特的学生
select `id`,`name` from student where address in ('呼和浩特');
-- 查询地址为空的学生
-- ====================== null not null ========================
select `id`,`name` from student where address = '';
-- 查询有出生日期的同学
select `id`,`name` from student where birthday is not null;
-- 查询没有出生日期的学生
select `id`,`name` from student where birthday is null;
4.4 contingency table query
JOIN contrast
-- ======================== 联表查询 ==========================
-- 查询,同学的学号,姓名,年级
select * from student;
select * from grade;
/*
1.分析需求,分析查询的字段来自哪些表,(连接查询)
2.确定使用哪种连接查询? 7种
确定交叉点(这两个表中哪个数据是相同的)
判断的条件:学生表中 gradeid = 成绩表 gradeid
*/
select id,name,s.gradeid,gradename
from student as s
inner join grade as g
where s.gradeid = g.gradeid;
-- right join
select `id`,`name`,s.gradeid,`gradename`
from student s
right join grade g
on s.gradeid = g.gradeid;
-- left join
select `id`,`name`,s.gradeid,`gradename`
from student s
left join grade g
on s.gradeid = g.gradeid;
operating | description |
---|---|
Innre join | If there is at least one match in the table, it returns OK |
left join | Even if there is no match in the right table will return all the values from the left table |
right join | Even if there is no match left table will return all the values from the right table |
-- join (连接的表) on (判断条件) 连接查询
-- where 等值查询
Since the connection
Their own tables and table joins, core: a table split in two tables can be the same
father
categoryid | categoryName |
---|---|
2 | information Technology |
3 | Software Development |
5 | art design |
Subclass
pid | categoryid | categoryName |
---|---|---|
3 | 4 | database |
2 | 8 | Office Information |
3 | 6 | web development |
5 | 7 | art design |
Action: Query subclass relationships corresponding parent
father | Subclass |
---|---|
information Technology | Office Information |
Software Development | database |
Software Development | web development |
art design | ps技术 |
-- ============================= 自连接 ==================================
create table category (
categoryid int(10) unsigned not null auto_increment comment '主题id',
pid int(10) not null comment '父id',
categoryName varchar(50) not null comment '主题名字',
primary key (`categoryid`)
) engine = InnoDB auto_increment = 9 default charset = utf8;
insert into category values
(2,1,'c语言'),(3,1,'JavaSE'),(4,3,'JavaEE'),
(5,1,'web开发'),(6,3,'操作系统'),(7,5,'数据结构'),
(8,2,'离散数学');
-- 查询父子信息:把一张表看成两个一模一样的表
select a.categoryName as '父栏目', b.categoryName as '子栏目'
from `category` as a,
`category` as b
where a.categoryid = b.pid;
SELECT语法
SELECT [ALL | DISTINCT]
{* | table.* | [table.field1[as alias1][,table.field2[as alias2]][,....]]}
FROM table_name [as table_alias]
[left | right | inner join table_name2] -- 联合查询
[WHERE ...] -- 指定结果需要满足的条件
[GROUP BY ...] -- 指定结果按照哪几个字段来分组
[HAVING] -- 过滤分组的记录必须满足的次要条件
[ORDER BY ...] -- 指定查询记录按一个或多个条件查询
[LIMIT {[offset,]row_count | row_countOFFSET offset}];
-- 指定查询的记录从哪条至哪条
4.5 分页和排序
排序
-- ========================= 分页 排序 ===============================
-- 排序 : 升序 ASC , 降序 DESC
-- ORDER BY 通过哪个字段排序,怎么排
-- 根据密码排序
select `id`,`name`,`password`,s.`gradeid` from student s left join grade g on s.gradeid = g.gradeid
where not id = 1 order by password asc;
select `id`,`name`,`password`,s.`gradeid` from student s left join grade g on s.gradeid = g.gradeid
where not id = 1 order by password desc;
分页
-- 分页 语法:limit 起始值 页面的大小
-- 缓解数据库压力 (瀑布流)
-- 每页只显示5条数据
select `id`,`name`,`password`,s.`gradeid` from student s left join grade g on s.gradeid = g.gradeid
where not id = 1 order by password desc limit 0,3;
-- [pageSize:页面大小]
-- [(n - 1) + pageSize:起始值]
-- [n:当前页]
-- [数据总数/页面大小 = 总页数]
4.6 子查询
本质:在where语句中嵌套一个子查询语句
-- ===================== where ======================
-- 1.查询学号,姓名,密码,年级号,年级 根据降序排列
-- 方式一、连接查询
select `id`,`name`,`password`,s.`gradeid`,`gradename` from student s left join grade g on s.gradeid = g.gradeid
order by password desc;
-- 方式二、子查询 查询gradeid 小于2
select `name`,`password` from student s
inner join grade g on s.gradeid = g.gradeid where g.gradeid < 2;
-- 在上述基础上增加 学生名字中有王的
select `name`,`password` from student s
inner join grade g on s.gradeid = g.gradeid where g.gradeid < 2 and name like '%王%';
-- 子查询
select `name`,`password`
from student s where name like '%王%' and gradeid = (
select `gradeid` from grade where gradeid < 2 and s.gradeid = grade.gradeid
);