数据库的多表查询
对数据库表的数据到的维护DML
DML
SQL语句的一个分类,DML主要完成数据库表中数据的维护,即:添加、删除、修改
数据完整性实现
实体完整性
表中不能出现两行完全一样的数据
解决方案:给表中添加主键(id),让该列的值唯一
域完整性
表中的值必须正确,在mysql8.0之后,可以使用check关键字实现
引用完整性
两张表的数据进行相互参考
即:表中的主外键
自定义完整性
需要根据业务的定义相应列的数据规则
MySQL系统函数
函数分类:
多行函数:传入的参数是多行,返回值也是多行
单行函数:传入的参数是多行,返回值是单行的,即聚合函数
字符串函数
concat(str1,str2,...,strn) -- 拼接字符串串
insert() -- 插入字符串
substring(str,index,n) -- 截取指定字符串
left/right(str,n) -- 获取字符串最左/右边的n个字符
ltrim/rtrim(str) -- 去除最左/右边的空格
日期函数
curdate() --返回当前日期
curtime() --返回当前时间
now() --返回当前日期时间
dayofyear(date) -- 返回date为这一年的第几天
week(date)/weekofyear(date) -- 返回date为这一年的第几周(包含与不包含)
date_format(date,format) -- 返回字符串format格式化后的日期
date_add/sub(date, interval expr unit) --日期的相加/减
datediff(date1,date2) --日期差
流程函数
-- 如果条件为真,则返回t,否则返回f
if(condition,t,f)
-- 如果value1不为null,则返回value1,否则返回value2
ifnull(value1,value2)
-- 如果value1等于value2,null,否则返回value2
nullif(value1,value2)
--如果value等于value1则返回result1 ....
case value when value1 then result1
when vaule2 then result2
......
else result
end
-- 如果条件condition为真,则返回result1 ....
case when condition then result1
when condition then result2
else result
end
多表查询
子查询
嵌套查询:多个select语句嵌套,内层的子查询作为外层的查询条件
select * from student where id in (select sid from score)
连接查询
内连接
交叉连接 cross
也就是笛卡尔积
select * from student cross join score
自然连接 natural
也就是将相同的列拼接在一起
select * from student natural join score
指定字段连接 using
也就是将同名列的值相等进行映射
select * from student join score using(id)
指定条件连接 on
select * from student join score on student.id = score.sid
外连接
左外连接
左表中的数据全部处理,右表满足条件正常显示
select * from student left join score on student.id = score.sid
右外连接
右表数据全部显示,左表满足的正确显示,剩余的用null填充
select * from score right join student on student.id = score.sid
union连接查询
将多张表中的数据进行合并,且重复的数据只显示一条
select name,age from student
union all
select name,age from student1
其他查询
/*
如果>any,则大于any后面最小的结果
如果<all,则小于all后面最小的结果
*/
-- any查询
select sid,age from score where age > any(select age from score where age<= 50)
-- all查询
select sid,age from score where age < all(select age from score where age <= 50)