java学习笔记④MySql数据库--03/04 DQL查询

 

03 使用DQL查询数据(一)

04 使用DQL查询数据(二)

DQL 数据查询语言  select

select * 方式效率低

AS 取别名 (给字段取别名,给表取别名,给计算结果取别名)

as取别名时,可省略as

distinct 去重

所有字段一起不重复算一条记录

select version(); 查找mysql的版本

like: %和_的区别

 内连接 外连接 自连接

自连接实例:

select b.categoryName as "父栏目名称",a.categoryName as "子栏目名称"
from category as a 
INNER JOIN category as b on a.pid = b.categoryId
where a.pid is NOT NULL;

order by : 默认asc升序,desc降序排列

mysql的时间函数:

SELECT DATE_FORMAT(now(),'%Y年%m月%d日 %H时%m分%s秒');
#2019年02月25日 20时02分06秒

SELECT STR_TO_DATE('2019年02月25日 20时02分06秒','%Y年%m月%d日 %H时%m分%s秒');
#2019-02-25 20:00:06

mysql的聚合/统计函数:

count()  sum() avg()  min()  max()

count(StudentName)取StudentName不为null的总数

group by分组后,

having 对分组后结果进行二次分组

--查找 平均分在80分以上的学生姓名及平均分

select s.StudentName,avg(StudentResult) from result r 

inner join Student s on r.StudentNo = s.StudentNo

group by r.StudentNo 

having avg(StudentResult) > 80

null值的比较,和任意值比较都是false

null > 60 flase

null = 60 false 

null < 60 false

null  is null true

case--when--then -else -end

select StudentNo,StudentName,

case when sex=1 then "男" when sex=2 then "女" else "未知" end

from student 
--多个INNER JOIN 使用
SELECT res.StudentNo,stu.StudentName,sub.subjectName,res.SubjectResult
from result res 
INNER JOIN student stu on stu.StudentNo = res.StudentNo
INNER JOIN subject sub on sub.SubjectNo = res.SubjectNo
WHERE sub.SubjectName = "java"
ORDER BY res.StudentResult desc,res.StudentNo DESC
LIMIT 0,5;  
原文地址:https://www.cnblogs.com/givemeanorange/p/10425822.html