mysql数据库子查询

子查询

  • 基于列的子查询
  • 基于条件的子查询

基于列的子查询

在查询的列中,使用子查询

PS: 子查询 要求 必须返回 单列,单值

  • t_resource表名
  • r 表的别名
  • r.user_id = u.id 查询字段
-- 查询用户和上传的资源数量
select u.*,
(select count(1) from t_resource r where r.user_id = u.id)
from t_user u ;

基于条件的子查询

  • 关系条件子查询
  • in 子查询
  • exists 子查询

in 子查询

子查询 必须返回 单列 多行(包括单行)

-- 查询 每日最晚注册的用户信息
select * from t_user where create_time in 
(
select max(create_time) from t_user group by date_format(create_time, '%Y-%m-%d')
)

exists 子查询

子查询 不需要返回具体的内容,只要存在即可

select * from t_user t where  exists 
(
	select * from (
		select max(create_time) max from t_user  group by date_format(create_time, '%Y-%m-%d') 

	) k where k.max = t.create_time  
)

基于关系条件子查询

子查询 : 返回单列单值

-- 查询 大于平均年龄 的所有用户信息

select * from t_user where age > ( select avg(age) from t_user )

嵌套查询

将一个查询的结果、作为一个表进行查询 ,在使用的时候,需要对查询的结果起一个别名,作为表名

集合查询

— 并集 union , union all

并集: 将两个查询的结果进行合并, union 会对重复的数据、进行去重, union all 是直接合并

猜你喜欢

转载自blog.csdn.net/qq_40679091/article/details/109129754