Mysql学习历程(14)-查询

来源:互联网 发布:mysql组合主键 编辑:程序博客网 时间:2024/05/16 01:00

联合查询:将多次查询(多条select语句)在记录上进行拼接(字段不会增加)

语法:多条select 语句 构成;每一条select 语句获取字段数必须严格一致(字段类型可以无关)

select 语句1  

union [union 选项]

select 语句2


union选项:all 保留所有  ;distinct  去重(整个重复),默认的;


联合查询的意义:查询同一张表,但是需求不同,如查询学生信息,男生身高升序,女生身高降序;

多表查询,多张表结构完全一样,保存的数据(结构也是一样的);

在联合查询中,order by不能直接使用,需要对查询语句使用括号才行;若要order by生效,必须搭配limit才行,limit使用限定的最大数即可 如99999;

create table stu_inf(id int primary key auto_increment,number varchar(10),sex char(1),age int ,height  int)charset utf8;insert into stu_inf values(null,'001','女',17,158),(null,'002','女',23,178),(null,'003','女',19,165),(null,'004','男',22,183),(null,'005','男',17,173),(null,'006','男',25,178);(select * from stu_inf where sex='男' order by height asc limit 9999)union(select * from stu_inf where sex='女' order by height desc limit 9999)

子查询:在某个查询结果之上进行查询;

子查询有两种分类方式:按位置分类和按结果分类;

按位置分类:子查询在外部查询中出现的位置;

from子查询;where子查询;exists子查询;

按结果分类:根据子查询得到的数据进行分类(理论上任何一个查询得到的结果都可以理解为二维表)

标量子查询:子查询得到的结果是一行一列;

查询:子查询得到的结果是一列多行;

量子查询:子查询得到的结果是一行多列;这三个出现在where之后

表子查询:子查询得到的结果是多行多列;这个出现在from之后;


标量子查询:

select * from my_student where c_id=(select id from my_class where c_name='Java');

列子查询

select * from my_student where c_id in (select id from my_class);
列子查询返回结果比较多,一列多行,使用in作为条件匹配;MYSQL中几个类似的条件:all  ,some,any

=any 等于其中一个即可;  =all  为全部;

!=any 与!=some 一个意思 


行子查询

select * from my_student where (age,height)=(select max(age),max(height) from my_student);
(age,height)称之为元素;


表子查询:子查询返回的结果当作二维表使用;

select * from (select * from my_student order by height desc) as student group by c_id;


Exists子查询:判断某些条件是否满足(通常是跨表),exists是接在where之后;exists返回的结果是0或者1;

select * from my_student where exists (select * from my_class);









原创粉丝点击