当前位置: 首页 > news >正文

Java学习--MySQL

后端开发中,数据常存储在数据库中:

一、数据库基础

数据库:DataBase(DB),是存储和管理数据的仓库

1.1连接数据库

mysql -u用户 -p密码  [-h数据库服务器ip地址 -P端口号]

1.2 关系型数据库

关系型数据库(RDBMS: 建立在关系模型基础上,由多张相互连接的二维表组成的数据库。

create database 数据库名;

一个数据库可以创建多张表;

1.3 SQL语句通用语法

SQL语句可以单行或多行书写,以分号结尾。

SQL语句可以使用空格/缩进来增强语句的可读性。

MySQL数据库的SQL语句不区分大小写。

注释:

1. 单行注释: -- 注释内容 或 # 注释内容 (MySQL 特有 )
2. 多行注释: /* 注释内容 */

1.4 SQL分类

分类

全称

说明

DDL

Data Definition Language

数据定义语言,用来定义数据库对象(数据库,表,字段)

DML

Data Manipulation Language

数据操作语言,用来对数据库表中的数据进行增删改

DQL

Data Query Language

数据查询语言,用来查询数据库中表的记录

DCL

Data Control Language

数据控制语言,用来创建数据库用户、控制数据库的访问权限

二、数据定义语言(DDL)

2.1 查询数据库

查询所有数据库

show databases;

查询当前数据库

select database();

2.2 使用数据库

使用数据库

use 数据库名;

2.3 创建数据库

创建数据库

create  database [ if  not  exists ]   数据库名 ;

2.4 删除数据库

删除数据库

drop  database [ if exists ]   数据库名 ;
上述语法中的 database ,也可以替换成 schema 。如: create schema  db01;

2.5 创建表

create table  表名(
	字段1  字段类型  [ 约束 ]  [ comment  字段1注释 ] ,
	......
	字段n  字段类型  [ 约束 ]  [ comment  字段n注释 ] 
) [ comment  表注释 ] ;

例如:

create table tb_user(
    id int comment 'ID 唯一标识',
    username varchar(20) comment '用户名',
    name varchar(10) comment '姓名',
    age int comment '年龄',
    gender char(1) comment '性别'
) comment '用户表';

约束条件:

约束

描述

关键字

非空约束

限制该字段值不能为null

not  null

唯一约束

保证字段的所有数据都是唯一、不重复的

unique

主键约束

主键是一行数据的唯一标识,要求非空且唯一

primary  key

默认约束

保存数据时,如果未指定该字段值,则采用默认值

default

外键约束

让两张表的数据建立连接,保证数据的一致性和完整性

foreign  key

示例:

-- 创建(约束)
create table tb_user(
    id int primary key comment 'ID 唯一标识', -- 非空且唯一标识
    username varchar(20) not null unique comment '用户名',-- 非空且唯一
    name varchar(10) not null comment '姓名',-- 非空
    age int comment '年龄',
    gender char(1) default '男' comment '性别' -- 默认
) comment '用户表';

id非空且唯一标识(主键),自动增长(关键字:auto_increment )

id int primary key auto_increment comment 'ID 唯一标识', -- 非空且唯一标识

2.6 数据类型

三大类数据类型:数值类型,字符串类型,日期类型

2.6.1 数值类型
类型大小(byte)有符号(SIGNED)范围无符号(UNSIGNED)范围
tinyint1(-128,127)(0,255)
smallint2(-32768,32767)(0,65535)
mediumint3(-8388608,8388607)(0,16777215)
int4(-2147483648,2147483647)(0,4294967295)
bigint8(-2^63,2^63-1)(0,2^64-1)
float4(-3.402823466 E+383.402823466351 E+38)0 和 (1.175494351 E-38,3.402823466 E+38)
double8(-1.7976931348623157 E+308,1.7976931348623157 E+308)0 和 (2.2250738585072014 E-308,1.7976931348623157 E+308)
decimal   

示例:年龄无符号且不超过255岁

age tinyint unsigned

分数:小数位1位,可能整数为可能0-100,所以占4位

float(5,2):5表示整个数字长度,2 表示小数位个数
double(5,2):5表示整个数字长度,2 表示小数位个数
decimal(5,2):5表示整个数字长度,2 表示小数位个数


score double(4,1)
2.6.2 字符串类型
类型大小描述
char0-255 bytes定长字符串
varchar0-65535 bytes变长字符串
tinyblob0-255 bytes不超过255个字符的二进制数据
tinytext0-255 bytes短文本字符串
blob0-65 535 bytes二进制形式的长文本数据
text0-65 535 bytes长文本数据
mediumblob0-16 777 215 bytes二进制形式的中等长度文本数据
mediumtext0-16 777 215 bytes中等长度文本数据
longblob0-4 294 967 295 bytes二进制形式的极大文本数据
longtext0-4 294 967 295 bytes极大文本数据
char(10): 最多只能存10个字符,不足10个字符,占用10个字符空间AB性能高浪费空间
varchar(10): 最多只能存10个字符,不足10个字符, 按照实际长度存储ABC性能低节省空间
2.6.3 日期时间类型
类型大小(byte)范围格式
date31000-01-01 9999-12-31YYYY-MM-DD
time3-838:59:59 838:59:59HH:MM:SS
year11901 2155YYYY
datetime81000-01-01 00:00:00 9999-12-31 23:59:59YYYY-MM-DD HH:MM:SS
timestamp41970-01-01 00:00:01 2038-01-19 03:14:07YYYY-MM-DD HH:MM:SS

示例:

birthday date
update_time datetime

2.7 查询和修改表

查询当前数据库所有表:show tables;
查询表结构:desc  表名;
查询建表语句:show create table 表名;
添加字段:alter table 表名  add  字段名  类型(长度)  [comment  注释]  [约束];
修改字段类型:alter table 表名 modify  字段名  新数据类型(长度);
修改字段名和字段类型:alter table 表名 change  旧字段名  新字段名  类型 (长度)  [comment 注释]  [约束];
删除字段:alter table 表名 drop  column 字段名;
修改表名: rename table 表名 to  新表名;
删除表:drop table [ if exists ] 表名;

三、数据操作语言(DML)

DML英文全称是Data Manipulation Language(数据操作语言),用来对数据库中表的数据记录进行增、删、改操作。

3.1 添加数据(insert)

指定字段添加数据:insert into 表名 (字段名1, 字段名2)  values (值1, 值2);
全部字段添加数据:insert into 表名 values (值1, 值2, ...);
批量添加数据(指定字段):insert into 表名 (字段名1, 字段名2)  values (值1, 值2), (值1, 值2);
批量添加数据(全部字段):insert into 表名 values (值1, 值2, ...), (值1, 值2, ...);

示例:

-- DML
-- 插入数据 - insert
-- 1.为tb_emp表的所有字段插入值
insert into tb_emp(username,name,gender,create_time,update_time)
values ('wuji','张无忌',1,now(),now());


-- 2.为tb_emp表的所有字段插入值
insert into tb_emp(id, username, password, gender, image, job, create_time, update_time, entrydate, name)
values (null,'zhiruo','123','2','1.jpg',1,now(),
        now(),'2003-01-01','芷若');



insert into tb_emp values (null,'zhiruo2','123','2','1.jpg',
                           1,now(),now(),'2003-01-01','芷若');

-- 3.批量为tb_emp表的username,name,gender字段插入数据
insert into tb_emp(username,name,gender,create_time,update_time)
values ('weifuwang','韦一笑',1,now(),now()),
       ('xieshiwang','谢逊',1,now(),now());
  • 1.插入数据时,指定的字段顺序需要与值的顺序是一一对应的。
  • 2.字符串和日期型数据应该包含在引号中。
  • 3.插入的数据大小,应该在字段的规定范围内。

3.2 修改数据(update)

修改语句的条件可以有,也可以没有,如果没有条件,则会修改整张表的所有数据。
修改数据:update  表名  set  字段名1 = 值1 , 字段名2 = 值2 , .... [ where  条件 ] ;

示例:

-- DML:更新数据 --update
-- 1、将tb_emp 表的ID为1员工  姓名name字段更新为"张三"
update tb_emp set name = '张三' ,update_time = now() where id = 1;

-- 2.将tb_emp 表的所有员工的入职日期更为‘2010-01-01’
update tb_emp set entrydate = '2010-01-01' ,update_time = now();

3.3 删除数据(delete)

1.DELETE 语句的条件可以有,也可以没有,如果没有条件,则会删除整张表的所有数据。2.DELETE 语句不能删除某一个字段的值(如果要操作,可以使用UPDATE,将该字段的值置为NULL)

删除数据:delete  from  表名  [ where  条件 ];
  • 示例:
-- DML:删除数据  --delete
-- 1.删除tb_emp 表中ID为1的员工
delete from tb_emp where id = 1;

-- 2.删除tb_emp表中的所有员工
delete from tb_emp;

四、数据查询语言(DQL)

4.1 语法

select
	字段列表
from
	表名列表
where
	条件列表
group  by
	分组字段列表
having
	分组后条件列表
order by
	排序字段列表
limit
	分页参数

4.2 基础查询

* 号代表查询所有字段,在实际开发中尽量少用(不直观、影响效率)

查询多个字段:select  字段1, 字段2, 字段3  from   表名;
查询所有字段(通配符):select  *  from   表名;
设置别名:select  字段1  [ as  别名1 ] , 字段2  [ as  别名2 ]   from   表名;
去除重复记录:select  distinct  字段列表  from   表名;

示例:

-- 1.查询指定字段name,entrydate
select name,entrydate from tb_emp ;

-- 2.查询返回所有字段
select id, username, password, name, gender, image, job, entrydate, create_time, update_time from tb_emp;
-- (不直观,性能低)
select * from  tb_emp;

-- 3.查询所有员工的name,entrydate,并起别名(姓名、入职日期)
select name as '姓 名',entrydate as 入职日期 from tb_emp;

-- 4.查询已有的员工关联了哪种职位(不要重复)
select distinct job from tb_emp;

4.3 条件查询(where)

条件查询:select  字段列表  from   表名   where   条件列表 ;

常用运算符: 

比较运算符

功能

>

大于

>=

大于等于

<

小于

<=

小于等于

=

等于

<>  !=

不等于

between ... and ...

在某个范围之内(含最小、最大值)

in(...)

in之后的列表中的值,多选一

like  占位符

模糊匹配(_匹配单个字符, %匹配任意个字符)

is null

null

逻辑运算符

功能

and  或  &&

并且 (多个条件同时成立)

or  或  ||

或者 (多个条件任意一个成立)

not  或  !

, 不是

示例:

-- ===== DQL:条件查询 ====
-- 1.查询 姓名 为 杨逍 的员工
select * from tb_emp where name = '杨逍';

-- 2.查询 id 小于等于 5的员工信息
select * from tb_emp where id <= 5;

-- 3.查询 没有分配职位 的员工信息
select * from tb_emp where job is null;

-- 4.查询 有职位 的员工信息
select * from tb_emp where job is not null ;

-- 5.查询 密码不等于‘123456’ 的员工信息
select * from tb_emp where password != '123456';
select * from tb_emp where password <> '123456';

-- 6.查询 入职日期 在‘2000-01-01’(包含)到 ‘2010-01-01’(包含)之间的员工信息
select * from tb_emp where entrydate >= '2000-01-01' and entrydate <= '2010-01-01';
select * from tb_emp where entrydate between '2000-01-01' and '2010-01-01';


-- 7.查询 入职时间 在‘2000-01-01’(包含) 到 ‘2010-01-01’(包含)之间 且性别为女 的员工信息
select * from tb_emp where entrydate >= '2000-01-01' and entrydate <= '2010-01-01' and gender = 2;

-- 8.查询  职位是2(讲师),3(学工主管),4(教研主管) 的员工信息
select * from tb_emp where job = 2 or job = 3 or job = 4;

select * from tb_emp where job in (2,3,4);

-- 9. 查询 姓名 为两个字段的员工信息
select * from tb_emp where name like '__';

-- 10.查询 姓张 的 员工
select * from tb_emp where name like '张%';

4.4 聚合函数

语法:select  聚合函数(字段列表)  from   表名 ;

函数

功能

count

统计数量

max

最大值

min

最小值

avg

平均值

sum

求和

  • null值不参与所有聚合函数运算
  • 统计数量可以使用:count(*)   count(字段)   count(常量),推荐使用count(*)
  • COUNT(列名)表示的是查询符合条件的列的值不为NULL的行数
  • count(1) 返回直接查询符合条件的数据库的行 查询结果跟count(*)相同 但是没有优化

示例:

-- === DQL:分组查询 ==
-- 聚合函数 :不对null值进行运算
-- 1.统计企业员工数量 -- count
-- A.count(字段)
select count(id) from tb_emp; -- 29
select count(job) from tb_emp; -- 28

-- B.count(常量)
select count(1) from tb_emp;

-- C.count(*)
select count(*) from  tb_emp;

-- 2.统计企业最早入职的员工
select min(entrydate) from tb_emp;

-- 3.统计企业最迟入职的员工
select max(entrydate) from tb_emp;

-- 4.统计企业员工 ID 的平均值
select avg(id) from tb_emp;

-- 5.统计企业员工的 ID 之和
select sum(id) from tb_emp;

4.5 分组查询(group by)

where与having区别

  • 1.执行时机不同:where是分组之前进行过滤,不满足where条件,不参与分组;而having是分组之后对结果进行过滤;
  • 2.判断条件不同:where不能对聚合函数进行判断,而having可以。
分组查询:select 字段列表 from 表名 [where 条件] group by 分组字段名 [having 分组后过滤条件];

示例:

-- 分组
-- 1.根据性别分组,统计男性和女性员工的数量 --count(*)
select count(*) from tb_emp group by gender;

-- 2.先查询 入职时间在'2015-01-01'(包含)以前的员工,
-- 并对结果根据职位分组,获取员工数量大于等于2的职位
select job,count(*) from tb_emp where entrydate <= '2015-01-01'  
                                group by job having  count(*)>=2;
  • 分组之后,查询的字段一般为聚合函数和分组字段,查询其他字段无任何意义。
  • 执行顺序: where  >  聚合函数 > having

4.6 排序查询(order by)

如果是多字段排序,当第一个字段值相同时,才会根据第二个字段进行排序。

条件查询:select 字段列表 from 表名 [ where 条件列表 ] [ group by 分组字段 ] order by 字段1 
排序方式1 , 字段2  排序方式2 

排序方式:(1)ASC:升序(默认值);(2)DESC:降序;

示例:

-- ====排序查询====
-- 1.根据入职时间,对员工进行升序排序
select * from tb_emp order by entrydate asc ;
select * from tb_emp order by entrydate ; -- 默认升序

-- 2.根据入职时间,对员工进行降序排序
select * from tb_emp order by entrydate desc ;

-- 3.根据 入职时间 对公司的员工进行 升序排序 ,入职时间相同, 
-- 再按照 更新时间 进行降序排序
select * from tb_emp order by entrydate ,update_time desc ;

4.7 分页查询(limit)

分页查询:select 字段列表 from 表名 limit 起始索引, 查询记录数 ;
  • 1.起始索引从0开始,起始索引 = (查询页码 - 1)* 每页显示记录数。
  • 2.分页查询是数据库的方言,不同的数据库有不同的实现,MySQL中是LIMIT
  • 3.如果查询的是第一页数据,起始索引可以省略,直接简写为 limit 10
-- == 分页查询 ==
-- 1. 从 起始索引0 开始查询员工数据,每页展示5条数据
select * from tb_emp limit 0,5;

-- 2.查询 第1页 员工数据,每页展示5条记录
select * from tb_emp limit 5;

-- 3.查询 第2页 员工数据 ,每页展示5条记录
select * from tb_emp limit 5,5;

-- 4.查询 第3页 员工数据 ,每页展示5条记录
select * from tb_emp limit 10,5;

4.8 if  和 case when

(1)if(表达式, tvalue, fvalue):当表达式为true时,取值tvalue;当表达式为false时,取值fvalue;

(2)case  expr  when  value1  then  result1 [when  value2  then  value2 ...] [else  result]  end

示例:

-- if(条件表达式,true取值,false取值)
select if(gender = 1,'男性员工','女性员工'),count(*) 
from tb_emp group by gender ;


-- case 表达式 when 值1 then 结果1 when 值2 then 结果2 ...else...
select (case job when 1 then '班主任' when 2 then '讲师'
    when 3 then '学工主管' when 4 then '教研主管' else '未分配职位' end)职位,
    count(*)
from tb_emp group by job;


4.9 多表设计

项目开发中,在进行数据库表结构设计时,会根据业务需求及业务模块之间的关系,分析并设计表结构,由于业务之间相互关联,所以各个表结构之间也存在着各种联系,基本上分为三种:(1)一对多(多对一);(2)多对多;(3)一对一;

4.9.1 一对多

一对多关系实现:在数据库表中多的一方,添加字段,来关联一的一方的主键。

示例:

create database db03;
use db03;

-- 部门表
create table tb_dept
(
    id int unsigned primary key auto_increment comment '主键ID',
    name varchar(10) not null unique  comment '部门名称',
    create_time datetime not null comment '创建时间',
    update_time datetime not null comment '修改时间'
) comment '部门表';

-- 员工表
create table tb_emp
(
    id          int unsigned primary key auto_increment comment 'ID',
    username    varchar(20)      not null unique comment '用户名',
    password    varchar(32) default '123456' comment '密码',
    name        varchar(10)      not null comment '姓名',
    gender      tinyint unsigned not null comment '性别, 说明: 1 男, 2 女',
    image       varchar(300) comment '图像',
    job         tinyint unsigned comment '职位, 说明: 1 班主任,2 讲师, 3 学工主管, 4 教研主管',
    entrydate   date comment '入职时间',
    dept_id     int unsigned comment '部门ID', -- 员工的归属部门
    create_time datetime         not null comment '创建时间',
    update_time datetime         not null comment '修改时间'
) comment '员工表';
4.9.2 外键约束
-- 创建表时指定
create table 表名(
	字段名 数据类型,
	...
	[constraint] [外键名称] foreign key (外键字段名) references 主表 (字段名)	
);
-- 建完表后,添加外键
alter table 表名 add constraint 外键名称 foreign key (外键字段名) references 主表(字段名);

示例:

alter table tb_emp
    add constraint tb_emp_tb_dept_id_fk
        foreign key (dept_id) references tb_dept (id);

4.9.3 一对一
  • 案例: 用户 与 身份证信息 的关系
  • 关系: 一对一关系,多用于单表拆分,将一张表的基础字段放在一张表中,其他字段放在另一张表中,以提升操作效率

-- 用户基本信息表
create table tb_user(
    id int unsigned  primary key auto_increment comment 'ID',
    name varchar(10) not null comment '姓名',
    gender tinyint unsigned not null comment '性别, 1 男  2 女',
    phone char(11) comment '手机号',
    degree varchar(10) comment '学历'
) comment '用户基本信息表';


-- 用户身份信息表
create table tb_user_card(
    id int unsigned  primary key auto_increment comment 'ID',
    nationality varchar(10) not null comment '民族',
    birthday date not null comment '生日',
    idcard char(18) not null comment '身份证号',
    issued varchar(20) not null comment '签发机关',
    expire_begin date not null comment '有效期限-开始',
    expire_end date comment '有效期限-结束',
    user_id int unsigned not null unique comment '用户ID',
    constraint fk_user_id foreign key (user_id) references tb_user(id)
) comment '用户身份信息表';
4.9.4 多对多
  • 案例: 学生 与 课程的关系

  • 关系: 一个学生可以选修多门课程,一门课程也可以供多个学生选择

  • 实现: 建立第三张中间表,中间表至少包含两个外键,分别关联两方主键

-- 学生表
create table tb_student(
    id int auto_increment primary key comment '主键ID',
    name varchar(10) comment '姓名',
    no varchar(10) comment '学号'
) comment '学生表';


-- 课程表
create table tb_course(
   id int auto_increment primary key comment '主键ID',
   name varchar(10) comment '课程名称'
) comment '课程表';


-- 学生课程表(中间表)
create table tb_student_course(
   id int auto_increment comment '主键' primary key,
   student_id int not null comment '学生ID',
   course_id  int not null comment '课程ID',
   constraint fk_courseid foreign key (course_id) references tb_course (id),
   constraint fk_studentid foreign key (student_id) references tb_student (id)
)comment '学生课程中间表';

4.10 多表查询

  • 多表查询: 指从多张表中查询数据
  • 笛卡尔积: 笛卡尔乘积是指在数学中,两个集合(A集合 和 B集合)的所有组合情况。(在多表查询时,需要消除无效的笛卡尔积)
-- 多表查询
select * from tb_emp,tb_dept;

4.10.1 内连接
隐式内连接:select  字段列表   from   表1 , 表2   where   条件 ... ;
显式内连接:select  字段列表   from   表1  [ inner ]  join 表2  on  连接条件 ... ;

示例:
-- ============================= 内连接 ==========================
-- A. 查询员工的姓名 , 及所属的部门名称 (隐式内连接实现)
select tb_emp.name,tb_dept.name from tb_emp,tb_dept
                                where tb_dept.id = tb_emp.dept_id;

-- B. 查询员工的姓名 , 及所属的部门名称 (显式内连接实现)
select tb_emp.name,tb_dept.name from tb_emp inner join tb_dept
                                    on tb_emp.dept_id = tb_dept.id;
4.10.2 外连接
左外连接:select 字段列表 from 表1 left [ outer ] join 表2 on 连接条件 ... ;
右外连接:select 字段列表 from 表1 right [ outer ] join 表2 on 连接条件 ... ;

示例:

-- =============================== 外连接 ============================
-- A. 查询员工表 所有 员工的姓名, 和对应的部门名称 (左外连接)
select e.name,d.name from tb_emp e left outer join tb_dept d on e.dept_id = d.id;

-- B. 查询部门表 所有 部门的名称, 和对应的员工名称 (右外连接)
select d.name,e.name from tb_emp e right join tb_dept d on d.id = e.dept_id;
4.10.3 子查询

介绍:SQL语句中嵌套select语句,称为嵌套查询,又称子查询。

形式:select * from t1 where column1 =  (select column1 from t2… );
子查询外部的语句可以是 insert / update / delete / select 的任何一个,最常见的是 select

相关文章:

  • leetcode日记(85)验证二叉搜索树
  • STM32 I2C驱动开发全解析:从理论到实战 | 零基础入门STM32第五十步
  • 蓝桥杯历年真题题解
  • 布朗运动(Brownian Motion):随机世界的舞者
  • C语言学习笔记-进阶(7)字符串函数3
  • 二分查找寻找旋转排序数组最小值边界条件处理
  • 【 <一> 炼丹初探:JavaWeb 的起源与基础】之 Servlet 过滤器:实现请求的预处理与后处理
  • 【GPT入门】第8课 大语言模型的自洽性
  • Mybatis Generator 使用手册
  • YCL4级python青少年人工智能水平测试复习资料
  • Java实现Consul/Nacos根据GPU型号、显存余量执行负载均衡
  • AI编程创新
  • 【机械臂】Windows 11安装Mujoco200并运行基于强化学习的多任务机械臂Meta-word基准
  • Python定时任务管理器
  • CUDA编程入门代码
  • VUE叉的工作原理?
  • mysql下载与安装、关系数据库和表的创建
  • 【LLM学习】1-NLP回顾+Pytorch复习
  • 如何快速辨别zip压缩包伪加密
  • 系统架构设计师—系统架构设计篇—微服务架构
  • 最近军事新闻热点/长沙seo排名外包
  • 佛山手机建网站/西安seo管理
  • 软件开发和编程的区别/电脑系统优化软件排行榜
  • 滨州北京网站建设/长沙官网优化公司
  • wordpress 拍卖/百度seo优化推广公司
  • java做的网站怎么设置关闭和开启网站访问不了怎么办/昆山网站建设