联合查询,子查询

联合查询

基本语句包括select 语句1   ,  union【union选项】   ,   select语句2。。。。

union选项   : all保留所有不管重复          distinct   去重  默认的

1 . select * from my_class 

union    --- 默认去重

select * from my_class

2. select * from my_class 

union   all   --- 不去重

select * from my_class

3. select id , c_name,room from my_class

union all ---不去重

select name,number,id from my_student

select * from my_student order by sex asc,height desc

--需求:男生升序,女生降序(年龄)   (select* from my_student where sex=' 男 ' order by age asc    limit  999999)            union           (select * from my_student where sex=' 女 ' order by age desc limit  999999)


子查询(sub query)

1 按位置分类       

from 子查询,

where子查询,

 exists子查询 。 select * from my_student where exists(select * from my_class)  ---是否成立

select * from my_student where exists(select * from my_class where id = 3)

select * from my_student where exist (select * from my_class where id = 2)


2 按结果分类      


[1]标量 子查询(一行一列),

select * from my_class              select * from my_student

select * from my_student where c_id=?     select id from my_class where c_name = 'Python1910'    ---id一定只有一个值(一行一列)

[2]列  子查询(一列多行),

select * from my_class                select * from my_student where c_id in(select id from my_class)

{  

1 。 =any等价于in   --其中一个就可以                    select * from my_student where c_id =  any(select id from my_class)          ---所有结果除了NULL除外

2。 any等价于some   ---二者是一样的select * from my_student where c_id =  some(select id from my_class)              ---所有结果除了NULL除外

3 。 == all为全部     select * from my_student where c_id =  all(select id from my_class)     ---NULL除外

}

---查询年龄最大且身高最高       select * from my_student where age = (select max(age) from my_student) and height = (select max(age) from my_student)


[3]行 子查询(多列一行或多行多列),select * from my_student where           --(age ,height)称为行元素       (age,height) = (select  max (age),max(height) from my_student)

select * from my_student order by age desc,height desclimit 1 --可能查询结果不是预想的


[4]表 子查询(多行多列)

---插入学生    insert into  my_student value(null,'bc200007','小红','23',''186)

--查找每个班身高最高的学生   select * from (select * from my_student order by height desc limit 999999 ) as student group  by c_id       -----每个班选出一个学生

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容