Mysql 基础2 (sql查询语句)

1 查询所有列

 select * from 表名;

2.查询指定列

 select 字段名1,字段名2 from 表名;

3.查询时添加常量

 select 字段名 as 常量名 from 表名;把字段名改为设置的常量名显示;

 select  常量值 as 常量名 from 表名;在表查询结果中新插入一列,字段名为设置的常量名,值为设置的常量值;

4.查询时合并列

select (字段1+字段2)from 表名 ; 只能合并数值类的字段

5.去重查询

select distinct 字段名 from 表名;

6.条件查询(where)

select 字段名 from 表名 where 字段名=字段值;

关键字 : 逻辑条件  and   or

                 比较条件  >  <      >=     <=    <>(非等于)   between and (等价于 >= and <=)

注意 判断null 值的时候 用关键字 is (等于) is not(不等于);

7.模糊查询

关键字     like   %(代表任意字符)          ——(代表一个字符);

例子 : 从student 表中查询姓张的同学

             select * from student where name like '张%';

            从student 表中查询姓张且名字是两个字的的同学

              select * from student where name like'张——';

8.聚合查询

常用聚合函数  sum()     avg()  max()  min()   count()

select 函数名 (字段名) from 表名 ;

注意用count()计数不包括 null 值;

9.分页查询 limit  m , n

limit 的两个参数 第一个是相对第一行的偏移值 , 第二个是显示几行; 起始值从0开始;

查询student表前两条数据;

select * from student limt 0 2;

10.排序查询

关键字 order by         asc升序    desc降序

select * from 表名 order by 字段名 desc , 字段名asc;

当按照多个字段进行排序时,其实是先按第一个字段排序,在第一个字段相同的情况下再按第二个字段排,以此类推

11 .分组查询

关键字 group by

例子:select 字段名 from 表名 group by 字段名;

一般分组查询与聚合函数连用,聚合函数作用于 分组后每个组的整体;

12.分组后筛选 having

类似于where 但是 having 加在分组之后 分组前用where;

select 字段名 from 表名 group by 字段名 having id =1;

            

            

原文地址:https://www.cnblogs.com/lxzwhite/p/10270839.html