MySQL基础及sql语句

MySQL基础

MySQL

数据库开源免费,能够跨平台,支持分布式,性能也不错,可以和 PHP、Java 等 Web 开发语言完美配合,非常适合中小型企业作为 Web 数据库(网站数据库),其中数据存储在硬盘中

一、关键字:

关键字: 某字段或者多个字段能够唯一标识一条记录

主关键字: 某一个关键字能够唯一标识一条记录

候选关键字: 除了主键之外的其他关键字

外键: 值为其他表的主键值,可以为空但不能重复(一对一关系不能重复,一对多关系可以重复)

二、范式:

遵守级别越高,冗余度越低

第一范式: 字段不能再分(必须有)

第二范式:必须有主键(不必要一定要遵守)

第三范式:除了主键之外不能再有候选关键字(不必要一定要遵守)(不常用)

第四范式(不用)

三、关系:

一对一:两张表

一对多:两张表

多对多:需要使用至少三张表实现,只有外键的表叫做中间表或连接表

四、字段类型:

1、字符型:

char:20个字符的空间,无论写了几个字符,有一些浪费空间,但是实际开发中使用的是char,运行更快

varchar:仅占输入的字符大小的空间,是动态的,但是会占用CPU计算时间,运行慢;但是在保存的数据特别大时,必须使用varchar

2、整型:

int:4个字节

bigint:8个字节

tinyint:1个字节

smallint:2个字节

mediumint:3个字节

3、浮点型:

double:双精度

float:单精度

4、时间和日期型:

datetime:如’2020-7-27 14:20:53’

5、字节型:byte(不常用)

五、SQL语句:

1、四种SQL语句类型:

数据定义语言DDL、数据查询语言DQL、数据操纵语言DML、数控制功能DCL

2、SQL语句:

(1)创建表:

create table 表名(

内容:字段、类型 、主键外键等

)ENGINE=InnoDB DEFAULT CHARSET=utf8;

例1:创建简单表:

create table teacher
(
   id int primary key auto_increment,
   name char(8),
   birth datetime,
   price float
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

例2:创建有字段约束的表:

create table person2
(
   id int primary key auto_increment,
   no char(12) unique not null,
   name char(8)  not null,
   birth datetime ,
   price float default 23.2
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

(2)根据关系创建表:

1、一对一关系:

例3:一对一:

drop table if exists wife;
drop table if exists husband; 

create table `husband` (
  `id` int primary key AUTO_INCREMENT,
  `name` char(20) ,
  `age` int 
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

CREATE TABLE `wife` (
  `id` int(11) primary key  AUTO_INCREMENT,
  `name` char(20),
  `age` int,
  `h_id` int unique,
     FOREIGN KEY (`h_id`)REFERENCES `husband` (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

2、一对多关系:

例4:一对多:

DROP TABLE IF EXISTS `employee`;
DROP TABLE IF EXISTS `company`;

CREATE TABLE `company` 
(
	 `id` int(11) PRIMARY KEY AUTO_INCREMENT,
	`name` char(20) DEFAULT '长月科技'
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

CREATE TABLE `employee` (
 	`id` int PRIMARY KEY  AUTO_INCREMENT,
	`no` int UNIQUE,
 	`name` char(20),
	`sex` char(2) ,
	`pwd` char(16) ,
	`company_id` int,
	 FOREIGN KEY (`company_id`)   REFERENCES `company` (`id`)
)

ENGINE=InnoDB  DEFAULT CHARSET=utf8;

3、多对多关系:

例5:多对多:

DROP TABLE IF EXISTS  stu_course;
DROP TABLE IF EXISTS  course;
DROP TABLE IF EXISTS  stu;

create table course
(
   	id int primary key auto_increment,
	course_name char(20)	
)engine=InnoDB  default charset=utf8;

create table stu
(
	id int primary key  auto_increment,
	name char(20),
	sex char(2)
)engine=InnoDB  default charset=utf8;

create table stu_course
(
    stu_id int,
    course_id int,
    foreign key(course_id) references course(id),
    foreign key(stu_id) references stu(id)
)engine=InnoDB  default charset=utf8;

(3)增删改查

1、增:

insert into 表名(已有表项) values(该表项要添加的值)

其中,表项可以有多个,使用逗号隔开,写了几个表项就在values后面写多少个值

例6:增加数据:

insert into stu(name) values('小明');
insert into stu(name, sex)values('王二', '女');
insert into stu(name, sex, birth) values('小李', '女', '1990-05-21 14:11:03');
insert into stu(id, name, sex, birth) values(100, '小李', '女', '1990-05-21 14:11:03');

2、删:

delete from 表名 where 条件

例7:从表中删除数据:

delete from stu where sex='男';

3、改:

update 表名 set 表项及其值 and 表项及其值 where 更改范围的条件

例8:更新表中内容:

update stu set sex='女', name='王大大' where id>10000

4、查:

select 字段 from 表

例如最简单的查询:

查询所有:
select * from stu;
查询某个字段:
select name from stu;
查询多个字段:
select id, name from stu;

select 字段 from 表 where 查询条件

查询id大于2的所有学生信息:
select * from stu where id > 2

常见的where后面可以使用的条件:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-unnKkdYf-1595932999920)(C:\Users\lenovo\AppData\Roaming\Typora\typora-user-images\1595924351547.png)]

例8:查询id在2到9之间的学生信息:

方法1:
select * from stu where id >= 2 and id <= 9;

方法2:
select * from stu where id between 2 and 9;

select 字段 as 查询结果中的字段名 from 表,as也可以省略

 select id as myid, name , grade as mygrade from stu;
 select id myid, name , grade mygrade from stu;

(一)、模糊查询:

在where后面接like 可以进行模糊查询,like又两种方式:

%:匹配0到多个字符

_:匹配一个字符

语法:…where like ‘%某个字符%’

例9:模糊查询:

select * from stu where like '_p%';

select * from stu where like '%n%';

(二)、标量函数(在mysql中可以写成小写)

LCASE():将某个字段转换成小写,仅对英文字段起作用

select lcase(name), sex, birth from stu;

UCASE():将某个字段转换成大写,仅对英文字段起作用

select ucase(name), sex, birth from stu;

length():返回某个文本字段的长度

select length(name) myname, sex, birth from stu;

MID():从某个文本字段提取字符

select mid(name, 2,1), sex, birth from stu;
select mid(name, 2,1), sex, birth from stu;

ROUND():对某个字段进行指定小数位数的四舍五入

NOW():格式化某个字段的显示方式,也可以获取当前时间,常与date_format()一起使用;

date_format():格式化时间

#显示的格式例子:2020-7-28 14:20:10 相当于字段的datetime格式
select now();
select id, name, sex, birth, now() now from stu;
#仅显示年份最后两位
select name,sex, birth, date_format(now(),'y%') from stu;
#显示完整的四位数年份
select name,sex, birth, date_format(now(),'%Y') from stu;
#格式化datetime格式字段的年份,同理还有月份等
select name,sex, birth, date_format(now(birth),'%Y') from stu;
select name,sex, date_format(birth,'这是%Y年%m月') birth, date_format(now(),'%Y')now from stu;
select name,sex, date_format(birth,'%Y:%m:%d') birth, date_format(now(),'%Y')now from stu;
select name,sex, date_format(birth,'%Y-%m-%d') birth, date_format(now(),'%Y')now from stu;
select name,sex, date_format(birth,'%Y-%m-%d %H:%i:%S') birth, date_format(now(),'%Y')now from stu;
格式 描述
%d 月的天,数值(00-31)
%Y
%H 小时 (00-23)
%h 小时 (01-12)
%i 分钟,数值(00-59)
%j 年的天 (001-366)
%M 月名
%m 月,数值(00-12)
%S 秒(00-59)
%u 周 (00-53) 星期一是一周的第一天

date_format()还可以写在where后面当作筛选条件:

select * from stu where date_format(birth, '%Y')=2020;

TIMESTAMPDIFF():时间差

#year = now().year - birth.year,可以直接获得值也可以用于条件比较
select * from stu where timestampdiff(year, birth, now())<20;
select id,name, sex, timestampdiff(year,birth, now()) from stu;
格式 描述
FRAC_SECOND 表示间隔是毫秒
SECOND 秒
MINUTE 分钟
HOUR 小时
DAY 天
WEEK 星期
MONTH 月
QUARTER 季度
YEAR 年

(三)、聚合函数

avg():返回平均值

select count(*)num, avg(id)  from stu;

count():返回记录条数,或者返回分组的记录条数,常与group by 字段 结合使用

group by 字段名:根据字段对表进行分组

#将整个表当作一个组,返回整个组的记录条数
select count(*) from stu;
#对当前组的某个字段返回记录条数
select count(birth) from stu;
#根据sex对表进行分组,查找每个组的记录条数
select count(*)num from stu group by sex;
#分组后可以查找整个分组中值都相同的字段
select sex, count(*)num from stu group by sex;

max():返回最大值

select count(*)num, max(id)  from stu;
select count(*)num, max(id)  from stu group by sex;
select sex,count(*)num, max(id)  from stu group by sex;

min():返回最小值

select count(*)num, min(id)  from stu;

sum():返回总和

select count(*)num, sum(id)  from stu;

(四)、分页

limit 起始索引, 页面最多记录条数

当只写一个参数时,相当于只取表中的n项显示

例10:使用limit完成分页

#仅显示一条记录
select * from stu limit 1;
#仅显示满足条件的1条记录
select * from stu where sex='男' limit 1;
#将整个表分5页显示,每一页的起始索引 = (当前页码 - 1)* 每页显示记录条数
select * from stu limit 0,4;
select * from stu limit 4,4;
select * from stu limit 8,4;
select * from stu limit 12,4;
select * from stu limit 16,4;


(五)乱序查询

使用rand()方法可以打乱表的顺序:order by rand()

#乱序查询
select * from stu order by rand();
#对符合条件的记录乱序排序并限制显示条数
select * from stu where id!=118 order by rand() limit 2;

(六)、having

having:筛选出符合条件的分组,可以填写select后面能够填写的内容,

select sex,count(*)num, max(id)  from stu group by sex having sex='女';
select sex,count(*)num, max(id)  from stu group by sex having count(*)>5;
select sex,count(*)num, max(id)  from stu group by sex having min(id)>5;

(七)查询语句执行过程:

1、from —— 2、where —— 3、group by —— 4、having —— 5、select —— 6、order by —— 7、limit

猜你喜欢

转载自blog.csdn.net/qq_42602282/article/details/107642633