MySQL——select查询

例表:

一、普通查询

无条件:

select * from student; 
/* "*" 的意思是打印表中所有字段,等同
select id,name,age,sex,grade_id,class_id 
from student;
*/

有条件:

select id,name 
from student
where age = 18; 
/* "where" 的意思是进行对字段筛选  */

 

二、去重查询(distinct)

/*
  distinct 去重查询,顾名思义就是去掉重复数据
*/
select distinct age from student;

三、排序查询

order by(升序ASC、降序DESC)

/*
    order by  排序:升序(ASC)、降序(DESC)。
*/
select distinct id,name,age from student
order by age ASC;

select distinct id,name,age from student
order by age DESC;

四、分组查询

group by(分组)

/*
    SUM()求和
*/
select id,name,SUM(score) 
from course
group by id;

五、多表查询

等值查询:

select name,course_name,score
from student,course
where student.id = course.stu_id
    and age <= 20
    and score < 60;

六、连接查询

外连接:

1、左连接查询(左表数据全部存在)

select name,course_name,score
from (  select id,name
        from student
        where age<=20
     )a 
left join
     (
        select stu_id,score
        from course
        where score<60                 
     )b
on a.id = b.stu_id
where score is not null;

2、右连接查询(保留右表满足条件数据,左表补NULL)

select name,course_name,score
from (  select id,name
        from student
        where age<=20
     )a 
right join
     (
        select stu_id,score
        from course
        where score<60                 
     )b
on a.id = b.stu_id
where name is not null;

3、全连接查询(保留左右满足条件的数据)

select name,course_name,score
from (  select id,name
        from student
        where age<=20
     )a 
full join
     (
        select stu_id,score
        from course
        where score<60                 
     )b
on a.id = b.stu_id
where name is not null 
      and score is not null;

内连接:(只有完全匹配才会保留)

select name,course_name,score
from (  select id,name
        from student
        where age<=20
     )a 
inner join
     (
        select stu_id,score
        from course
        where score<60                 
     )b
on a.id = b.stu_id;

七、联合查询(union,union all)

联合结果集不必受被联合的多个结果集之间的关系限制,不过使用UNION仍然有两个基本的原则需要遵守:
1.每个结果集必须有相同的列数;
2.每个结果集的列必须类型相容,即结果集的每个对应列的数据类型必须相同或者能够转换为同一种数据类型。

联合查询Union又有Union和Union All两种方式,下面分别说下他们的用法以及区别:

select stu_id,course_name,score
from course
where score<60

Union  --union联合查询:有去重功能
  
select stu_id,course_name,score
from course
where score>=90;
select stu_id,course_name,score
from course
where score<80

Union all --union all联合查询:将所有数据都存入结果集
select stu_id,course_name,score
from course
where score>=70;

union有去重复的功能,union all没有去重复功能,所以union的效率会低点,如果查询的结果集没有要求去重或者联合表中不存在重复数据 建议使用union all操作。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值