SQL语句,精简版

显示所有的数据仓库:show databases;   注意:书写的所有sql语句, 要求结尾必须有分号。

使用mysql这个数据库(切换数据库):use mysql;

创建一个名称为mydb1的数据库:
create database mydb1;

创建一个使用utf8字符集的mydb2数据库:
create database mydb2 character set utf8;


删除数据库:drop database 数据库名;


修改数据库编码集:
alter database 数据库名称 character set 字符集;

查询当前正在使用的数据库:
select database();


查看指定数据库建表语句及字符集:
show create database  数据库名;


语法:use 数据库名;
创建数据库表的语法:
语法:
create table 表名(
列名 类型(长度), ----某一列,存放的数据是什么类型.长度表示允许列名存储数据的最大长度.
列名 类型(长度),
..........................
列名 类型(长度)---最后一个列不需要逗号。
);


(****通常我们不会把文件存储到数据库。(占用资源,操作速度慢)
我们会把文件的路径(通常存放在本地磁盘)存到数据库中。****)


查看该数据库的所有的表
show tables;

查看表的列的信息(查看表结构)
desc 表名;

主键约束:primary key 列的数据 不允许重复的,并且不为空

自增长 auto_increment  表的主键是int 类型

唯一约束:unique :
该列(字段)的值不允许重复。可以为null(null不算重复)


修改数据表:
alter table 表名 增/删/改 列名 类型(长度) 约束;

增加列语法
alter table 表名 add 列名 类型(长度) 约束;
alter table emp2 add salary double;


修改现有列类型、长度和约束
alter table 表名 modify 列名 类型(长度) 约束;
alter table emp2 modify birthday date not null;
alter table emp2 modify name varchar(60) unique not null;

修改现有列名称
alter table 表名 change 旧列名 新列名 类型(长度) 约束;
alter table emp2 change name username varchar(60) unique not null;

删除现有列语法:
alter table 表名 drop 列名;
alter table emp drop age;


修改表名 语法:rename table 旧表名 to 新表名
rename table emp2 to person;


修改表的字符集 语法:alter table 表名 character set 编码集;
show create table emp;//查询此时表的编码
改:alter table emp character set utf8;

//数据表删除
drop table 表名;
drop table emp;


查询表中所有信息
select * from 表名;


向表中插入数据
(所有列去全部被定义)
第一种语法:insert into 表名 (列名1,列名2,列名3......)  values (值1,值2,值3......);
insert into person(id,username,password,gendar,birthday,salary)
values(null,'zhangsan',123,'nan','1992-8-19',12000);
(部分列选择定义,注意非空必须定义,且受唯一约束的,不可重复添加到数据库)
第二种语法:insert into 表名(列名,列名,列名。。。。) values(值,值,值。。。。)
注意:在插入数据的时候,如果某些列可以为null,或者是自动增长的列,或者有默认值的,在插入的时候可以省略。
insert into person(username,password,birthday) values('suoge',123,'1995-10-19');
(省略列名,只需要全部提供,经常用到***)
第三种语法()
insert into 表名 values(值,值,值,值);
如果给表中的所有列插入数据,这时可以省略表名后面的列名,直接写values。
insert into person values(null,'wangwu',123,'nv','1987-8-9',13000);

更改表中的数据
语法: update 表名 set 列名=值,列名=值.... [ where条件语句 ]; 
1.将所有人的密码改为abcdef
update person set password ='abcdef';(where相当于if)
2.将姓名为张三的薪资改为8888
update person set salary =88888 where username ='张三';
3.将id为3的人姓名改为赵六,密码改为zhaoliu
update person set username='赵六',password='zhaoliu' where id = 3;
4.将张三的年龄在原基础上增加2
update person set age = age + 2 where username = "张三";

删除表中的数据
语法:delete from 表名 [where条件语句]
1.删除表中名字为zhaoliu的记录
delete from person where username='zhaoliu';
2.删除年龄是30岁的员工
delete from person where age='30';
3.删除表中的所有记录
dele from person;


删除表记录:truncate table person;(表中数据全部干掉,自建新的一模一样的表)


delete 和 truncate 区别?
1.
(1).delete删除是一条记录一条记录逐行删除
(2).truncate直接将表删除,然后在新建一张同样的表
2.
(1)删除数据可以回退(可以找回数据)
(2)删除数据不能回退(不可以找回数据),但是删除数据比delete快

dele from person;  和 drop table user;区别?
1.delete 删除是一条记录一条记录逐行删除,表还在,但是数据记录不见了
2.drop删除,表不存在了



SQL分类
DDL(数据定义语言)
如:create drop alter truncate

DML(数据操纵语言)
如:update insert delete (注意:不包含查询)

DCL(数据控制语言) 
如:grant revoke  if...else...  begin transaction

DQL(数据查询语言)
如:select



select查询
select * from 表名;  //显示表中所有行和列的信息

select 列名,列名..from表名;  //显示指定列数,列出指定行信息

1.查询所有学生到的姓名和成绩
select name,score from student;

按条件查询
select 列名,列名...from 表名 where 条件;
说明:查询符合where条件的数据
作用:过滤,只有符合条件的,才去列出相应的信息

2.查询表中年龄大于等于24岁的学生信息
select * from student where age>=24;

运算符:
1)>(大于)  <(小于)  >=(大于等于)  <=(小于等于)  =(相等)  <>或者!= (不相等) 

3.查询年龄不是25岁的学生
select * from student age <> 25; //标准写法


and逻辑与 ,多个条件同时成立
or逻辑或,多个条件任意一个成立
not逻辑非,相反的意思

4.查询年龄>23,并且成绩>80的同学信息
select * from student age>23 and score>80;


5.查询成绩在80~100(包含)之间的学生信息
select * from student score>=80 and score<=100;

区间:between ...  and ...在两者之间取值。 列名 between 开始值 and 结束值;
上面的可以转换为
select * from student score between 80 and 100;


in(值1,值2,值3)在指定值中任意取;
如:in(70,80,90)值可以取70、80或者90
使用格式:
	where 列名 in(值1,值2,值3);
	等价于
	where 列名 = 值 or 列名= 值 or 列名=值...

6.查询年龄为18,23,25的同学信息
select * from student where age=18 or age=23 age 25;
select * from student where age in (18,23,25);



模糊查询:like'模糊查询部分'
like'*%'
like'*_'
% 表示零或任意多个字符
_任意单个字符
例:name like '张%'所有姓张学员
    name like '%张%'只要有张就可以。
    name like '张_'所有姓张名字为两个字学员
    name like '_张_'只有中间是张,前面一个字,后面一个字。

7.查询所有含有岩的学生信息
select * from student where name like'岩%';


is null判断该列值是否为空

8.查询没有生日学员信息。就是生日是null。
select * from student where birthday is null;

9.查询有年龄学员的信息,就是年龄不是空
select * from student where age is not null;


过滤重复数据
查询排重:select distinct 列名 from 表名 {where 条件}
distinct 去重复。 显示distinct后面列的内容,并且过滤掉重复的数据

10.显示不重复的年龄
select distinct age from student;


对查询的结果进行排序
使用order by 子句排序查询结果
格式:select * from 表名 order by 列名1 (asc|desc),列名2(asc|desc),列名3(asc|desc)
按照列名1,列名,列名3 进行排序输出
asc升序排列  desc是降序  默认是asc升序

按照第一列进行排序,如果第一列相同,在按照第二列在进行排序,依次类推


注意:order by a asc,b asc
	a,b
	1,2
	1,3
	4,5
	3,1
排序结果
	1,2
	1,3
	3,1
	4,5

别名:可以对查询出来的列名起别名

11.给年龄和分数分别起别名
select age as 年龄,score as 分数 from student;
当然也可以省略关键字as
select age 年龄,score as 分数 from student;(不建议这么使用)


面试题:
1.select age,score from student;
2.select age score from student;
上述SQL语句有什么区别?
第一条给年龄和分数起别名,只是没写名字为默认的而已
第二条是给表的age命名为score,此时age列的别名是score


聚合函数:
count(数目) :统计个数(行数),统计有多少行,或者有多少条数据
sum(和)函数:求和
avg()函数:求平均值
max(最大值):求最大值
min(最小值):求最小值

count函数:
语法:select count(*)或者count(列名) from 表名;
一般建议使用*

注意:1.count(具体列名):在根据指定的列统计的时候,如果这一列中有
null的行,该行不会被统计在其中。按照列去统计有多少行数据。

2.select count(列名)from 表名 :按具体列来进行统计行数
select count(*) from 表名:统计表中的行数。


12.统计一个班共有多少学生
select count(*) from student;

13.查询成绩大于80的学生信息
select * from student where score>80;

14.统计成绩大于80的学生有多少个
select count(*) from student where score>80;


sum函数:
语法:select sum(列名),sum(列名),...from 表名;

注意:1.如果使用sum多列进行求和的时候,如果某一列中含有null,
这一列所在的行中的其它数据不会被加到总和中

15.统计一个班级成绩和
select sum(score) from student;

16.分别统计年龄和,成绩和
select sum(age),sum(score) from student;

17.统计年龄与成绩的总和值
select sum(age)+sum(score) from student;

select sum(age+score) from student; 这两个结果不同
必须进行判断
ifnull(列名,默认值)
select sum(ifnull(age,0) +ifnull(score,0)) from student;

truncate(列名,截取的小数位) 保留几位小数

select truncate(sum(ifnull(age,0) + ifnull(score,0)),2) from student;
截取两位数


avg函数:
语法:select avg(列名) from 表名;
注意:求某列的平均值,avg里面的null不作为统计。

18.求一个班级平均年龄
select sum(age)/count(*) from student; 正确
select sum(age)/count(age) from student;不正确
select avg(ifnull(age,0)) from student;  《《《主选 正确
注意:聚合函数不能组合在一起使用。

max,min函数
max(列名)/min(列名) 统计该列的最大值或者最小值
语法:select max(列名),min(列名) from 表名;

注意:null排除在外

20.求班级最高分和最低分
select max(score),min(score) from student;


group by分组函数(******非常重要)

21.查询购买的每种商品的总价
select product,sum(price) from orders group by product;
注意:分组特点:(按照正常逻辑来讲,商品有多件相同,但是价格不同,所以显示时显示其中的一个id都是不对的)
那么就有:分组最终显示的是*****被分组的列和聚合函数
1.先按照product进行分组,分组完成之后在给每一组进行求和


22.查询每一种商品的总价大于30的商品,并显示总价。
select product,sum(price) from student group by product having sum(price) >30;

where使用注意点:
1.where中不可以使用‘别名’
2.where中不可以使用聚合函数
3.where在**分组之前**进行条件过滤

having使用的说明:
1.having中可以使用别名
2.having中可以使用聚合函数
3.having在分组之后进行条件过滤

where和having有什么区别?
1.where在分组之前进行过滤,having在分组之后进行条件过滤
group by 和 having 组合使用。
2.where之后不可以使用别名和聚合函数,having中可以使用‘别名和聚合使用’。

开发小技巧:
当在需求中遇到每种,每个等字眼的时候就使用分组。


查询关键字的出现的顺序是固定:
select...要显示的内容...from...表名...where 条件...group by ...
分组的列 ...having...分组后的条件...order by...排序

select ⑤... from ...① where ...②...group by..③...having...④...order by..⑥

查询的执行顺序
1.from:表名
2.where:条件过滤
3.group by:分组
4.having:分组之后进行过滤
5.select:执行完毕之后,显示内容
6.order by:根据查询的内容进行排序输出


查询小结:**********
from表名

where 条件:
	逻辑运算符:and or not
	比较运算符:< > <= >= <> =
	在...之间:between...and...
	in():任意的一个条件成立即可
	is null/is not null
	模糊匹配:like% _
group by 列:对列进行分组

having条件:
	逻辑运算符:and or not
	比较运算符:< > <= >= <> =
	在...之间:between...and...
	in(set)
	is null/is not null
	模糊匹配:like% 
	聚合函数(sum,avg,max,min,count)

order by desc(降序)/asc(升序,默认)

数据库备份:
23.备份数据
1.打开一个新的dos窗口
2.输入命令
语法:mysqldump -u 用户名 -p 数据库名 >磁盘SQL文件路径
mysqldump -u root -p mydb3 > E:\mysql03.sql

注意:在备份数据的时候,数据库不会被删除。
可以手动删除数据库。同时在恢复数据的时候,不会自动的给我们创建数据库,仅仅只会恢复数据库
中表和表中的数据。

24.恢复数据
语法:mysql -u 用户名 -p 导入库名 < 硬盘的SQL文件绝对路径
1.创建一个数据库(准备把数据恢复进去)
2.打开一个新的dos窗口

mysql -u user -p newsql < e\:mysql03.sql


数据库多表设计
多对多:(开发中最常用)(需要设计中间表)
常见例子:程序员和项目的关系,顾客和商品的关系等

一个程序员可以参与多个型项目,一个项目可以被多个程序员开发
说明***:如果两张表是多对多的关系,需要创建第三张表,并在
第三张表中增加两列(另外两张表的主键),引入其他两张表的主键作为自己的外键
例如:
//创建程序员表
create table coder(
	id int primary key auto_increment,
	name varchar(50),
	salary double
);
//创建项目表
create table project(
	id int primary key auto_increment,
	name varchar(50)
)

//创建中间关系表
create table coder_project(
	coder_id int,
	project_id int,
	foreign key(coder_id) references coder(id);//外键约束
	foreign key(project_id) references project(id);
);
使用中间表的目的是维护两表多对多的关系:
1.中间表插入的数据 必须在多对多的主表中存在
2.如果主表的记录在中间表维护了关系,就不能随意删除。如果可以删除,
中间表就找不到对应的数据了,这样就没有意义了。


添加外键需注意:
1.如果从表要去添加一个外键约束,要求主表被引用的字段是主键或者唯一的。通常使用主键
2.如果要删除主表的数据。要求在从表中这个数据,要没有被引用,才可以删除。
3.如果要向从表中去添加数据。要求在主表中,要有对应的数据。才可以去添加。


外键约束作用:保持数据的完整性,和有效性。


一对多关系:
设计**:需要在多的一方增加一列,引入一的一方的主键作为自己的外键
例如:作者和小说关系,用户和订单的关系等。
一个作者可以写多部小说,但是每一部小说,只能对应具体的一个作者。


一对一关系
设计:可以在任意一方表中添加另一方的主键作为外键即可。
例如:一个老公对应一个老婆,一个老婆对应一个老公。


经典案例:设计学生成绩管理系统数据表(按照给定需求设计即可)
1.每个教师可以教多门课程     //
2.每个课程由一个老师负责	    //一对多
3.每门课程由多个学生选修		》
4.每个学生可以选修多门课程	》多对多
5.学生选修课程要有成绩

学生表
create table student(
	id int primary key auto_increment,
	name varchar(50)
)
老师表
create table teacher(
	id int primary key auto_increment,
	name varchar(50)
)
课程表
create table course(
	id int primary key auto_increment
	name varchar(50),
	teacher_id int,
	foreign key(teacher_id) references teacher(id)
)
中间表
create table course_student(
	student_id int,
	course_id int,
	score double,
	foreign key(student_id) references student(id);
	foreign key(course_id) references student(id);
)

全复习:
库的操作
创建库:create database 库名 character set 编码表;
删除库:drop database 库名;
查询库:show databases;
查看库的编码表:show create database 库名;
更改库:use 库名;
查看当前正在使用的库:select database();
修改库的编码表:alter database 库名 character set 编码表;

表本身的操作
创建表:create table 表名( 列名 列的类型(长度)  列的约束 ,列名 列的类型(长度)   列的约束...... );
删除表:drop table 表名;
查询表:show tables;
查看表的结构:desc 表名;
查看表的编码表:show create table 表名;
修改表:alter table 表名 增/删/改 列名 列的类型(长度) 约束;
add/drop/change/modify
修改表名:rename table 旧表名 to 新表名;


表中数据的操作
增:insert into 表名(列名) values(值);
删:delete from 表名 where 条件;  truncate 
改:update 表名 set 列名=值 ,列名=值 where 条件 ;
查:select 列名 as 别名 ,列名 as 别名。。。。 from 表名  where 条件;
查询排重:select distinct 列名 from 表名 where 条件;
Mysql中limit的用法:返回前几条或者中间某几行数据
select * from 表名limit 1,4。
1表示索引,注意这里的索引从0开始。
4表示查询记录数。
上述就表示从第2条记录开始查询,一共查询4条,即到第5条。

聚合函数:
count 统计个数、sum求和、avg 平均值、max、min
在使用这几个函数进行数据的统计分析时,有时需要对数据表中的列进行数据的分组处理。group by

分组 group by :

排序:order  by  asc | desc; 


多表查询:
笛卡尔积介绍(id*id 如两个表都是三行数据,查询出来就是3*3=9)
25.查询两张表中关于水果的信息,要显示水果名称和水果价格?
多表查询语法:select * from a,b;

直接查询的获得结果:
a表中的每一条记录,都和b表中的每一条进行匹配连接。所得到的最终结果是:a表中的条目数
乘以b表中的数据的条目数。
将a表的每行记录和b表的每行记录组合的记过就是笛卡尔积。

笛卡尔积缺点:查询到结果冗余了,里面有很多错误的数据,需要过滤。
(解决笛卡尔积:多表查询一定要添加条件)
内连接:(两表的公共部分)

隐式内连接查询
语法:
select 列名,列名...from 表名1,表名2 where 表名1.列名 = 表名2.列名;

如:select * from a,b where a.列名 = b.列名;

显示内连接查询
语法:
select * from  表名1 inner jion 表名2 on 条件;
如:select * from a inner jion b on a.id = b.id;

外连接查询:
外链接:左外连接、右外连接、全外连接、自连接

左外连接:
用左边表去右边的查询对应记录,不管是否找到,都将显示左边表中全部记录
举例:上述案例中虽然右表没有香蕉对应的价格,也要把他查询出来。
语法:select * from 表1 left outer 表2 on 条件;
如:select * from a left outer join b on a.id = b.id;
说明:把left关键字之前的表,是定义为左侧。left关键字之后的表,定义右侧。
查询的内容,以左侧的表为主,如果左侧有数据,右侧没有对应的数据,仍然会把左侧数据进行显示。


右外连接:
用右边表去左边表查询对应记录,不管是否找到,右边表全部记录都将显示
举例:上述案例中不管在左方表能否找到右方价格对应的水果,都要把右方的价格显示出来。

语法:select * from 表1 right outer join 表2 on 条件;
如:select * from a right outer join b on a.id = b.id;
说明:如果右侧有数据,左侧没匹配到,把右侧的数据显示出来。
right之前的是左侧,right之后的是右侧。

总结:
左外连接以关键字左侧数据为主,不管右侧的数据是否有对应,都把左侧的数据显示出来。
右边连接以关键字右侧数据为主,不管左侧的数据是否有对应,都把右侧的数据显示出来。


全外连接:

全外连接:左外连接和右外连接的结果合并
select * from 表1 full outer jion 表2 on 条件;
举例:select * from a full outter jion b on a.id = b.id;(mysql数据库不支持此语法)
(oracle 和 DB2及其他数据库是支持的)

引入union:
和并左右外连接进行查询,去掉重复的数据。
select * from a left outer join b on a.id = b.id 
union
select * from a right outer jion b on a.id = b.id;

全外连接(不去调重复的数据)结果:使用union all


多表查询小结快速看:
内连接:
1、隐式内连接:
Select * from a,b where a.id = b.id;
结果:C
2、显示内连接:
Select * from a inner join b on a.id = b.id;
结果:C

外连接:
1、左外连接
select * from a left outer join b on a.id = b.id
结果:A+C
2、右外连接
select * from a right outer join b on a.id = b.id
结果:B+C
3、union:相当于全外连接
select * from a left outer join b on a.id = b.id
union
select * from a right outer join b on a.id = b.id
	结果:A+B+C,会自动虑重

select * from a left outer join b on a.id = b.id
union all
select * from a right outer join b on a.id = b.id
结果:A+B+C,有重复数据 


关联子查询:
子查询定义:把一个sql的查询结果作为另一个查询的参数存在。
数据库有A水果表,B价格表
A水果表			B价格表
id	name		id	price
1	苹果		1	2.3
2	橘子		2	3.5
3	香蕉		4	NULL

25.查询价格最贵的水果名称
步骤:1.在B表中找最高的价格:
select max(price) from b;
2.在B表中找到最高价格对应的编号;
select b.id from b where b.price = 3.5;
3.在A表中根据编号找对应的水果名称;
select a.name from a where a.id in(2);

根据子查询完成上述的功能需求:
select a.name from a 
	where a.id in(select b.id from b
			where b.price = (select max(price) from b));			)

in的用法:
26.查询不及格的学生(使用in完成)
1.在中间表中查询不及格的学生编号
select student_id from student_course where score<60;
2.在学生表中根据学生编号查询学生信息
select * from student where id in
			(select student_id
			from student_course
			where score<60);

exists:(了解)
如果子查询有返回数据行,就认为是true,否则就认为是false
语法:select * from 表名 where exists(select ... from 表名 where 条件)

将外表中的查询结果拿到内表中去逐行判断条件是否成立,如果成立,取出该行结果。
说明:可以把exists原理理解为基础班学习过的嵌套循环,思想是一样的。

子查询定义:将某一条sql语句的执行结果作为另一条sql语句的查询条件。
28.查询不及格的学生
select * from student 
		where exists(select student_id
		from student_course
		where score<60 and student_course.student_id=student.id);
29.查询年龄最大的学生的信息
select * from student where age =(select max(age) from student);

select * from student where age >=all(select age from student);

any和some的使用方法(基本上一样)
any:表示任何一个
a>any(1,2,3) 等价于 a>1 或者 a>2 或者 a>3 --->等价于 a>min(1,2,3)

<any(1,2,3)  等价于 <1 or <2 or <3  等价于 <3   等价于 <max(1,2,3)  
30.查询成绩是90的学生的信息
select * from student where id =  any/some(
select student_id from studentcourse where
score =90); 

31.查询获得最高分的学生信息。
1).在中间表找最高分
2).在中间表中找最高分对应的学生编号
3).在学生表中根据学生编号找学生信息

select * from student where id in (
select student_id from studentcourse where
score = (select max(score) from studentcourse)
);

31.查询编号是2的课程比编号是1的课程最高成绩高的学生信息。
1).在中间表中 找编号是1的课程的最高成绩
2).在中间表中 找编号是2的成绩 > 编号 1最高成绩 的学生id;
3).在学生表中 根据学生的编号 找对应的学生信息

select * from student where id in(
	select student_id from studentcourse 
	where course_id = 2 and score>(select max(score) from studentcourse where course_id = 1) 
)

33.查询不及格的学生信息和不及格分数
(1)不及格分数
select * from studentcourse where score<60;
(2)将查询的结果表作为临时表和student学生表进行多表关联查询
select student.* ,temp.score from student,(select * from studentcourse where score<60) as temp
where id = student_id;
分析:
select * from a,b where 条件;
select * from student,(结果表) as temp where id = student_id;

注意:如果要将查询的结果表作为多表关联查询,必须要将结果表当做临时表来使用。


limit 限制查询结果返回的数量
格式1:select * from 表名 limit 数量;
格式2:select * from 表名 limit [偏移量],数量;(分页查询可以用到)(从偏移量之后开始返回数据)

34.查询数学成绩比语文成绩高的所有学生信息。
1.先拿数学的id
select id from course where name ='数学';
select id from course where name = '语文';
2.根据课程id从中间表中获取对应课程的所有信息
select * from student_course 
where id = (select id from course where name ='数学');
select * from student_course 
where id = (select id from course where name ='语文');

多表关联语句:select* from a,b where 条件;
select * from () as temp1,() as temp2 
	where temp1.student_id = temp2.student_id
		and temp1.score> temp2.score; 

查询结果语句:(注意相同的字段要指定表名,否则就报错)
select temp1.student_id from (select * from student_course 
where id = (select id from course where name ='数学')) as temp1,(select * from student_course 
where id = (select id from course where name ='语文')) as temp2 
	where temp1.student_id = temp2.student_id
		and temp1.score> temp2.score; 
将以上的查询结果(1,5,6)作为student表的条件查询对应的学生信息
select * from student where id in(select temp1.student_id from (select * from student_course 
where id = (select id from course where name ='数学')) as temp1,(select * from student_course 
where id = (select id from course where name ='语文')) as temp2 
	where temp1.student_id = temp2.student_id
		and temp1.score> temp2.score);


自带函数:(了解)
select password('abc');加密
---String ->substring
select substring('王思聪',2,2); 参数1:源  参数2:偏移量  参数3:长度

--Math ->abs,ceiling,floor,round
select abs(-88);
select ceiling(8.1);
select floor(8.9);
select round(8.5);
--时间/日期 ->Date,SimpleDateFormat,Calendar
select now();
select current_time();
select current_date();
select year(now());

猜你喜欢

转载自blog.csdn.net/JH_OMEH/article/details/81333940