查询数据(**)

2018-05-17  本文已影响0人  我是邱邱

1.查询所有列

select * from 表名;

2.查询指定列

 select  列名1,列名2   from  表名;

3.查询指定别名

select  列名1  as  ‘ 别名1’,列名2 as  ‘别名2’   from  表名  as  ‘表名’;(表的别名不可以有中文,在多表查询中经常使用表的别名)

4.查询时添加常量列

例如:在查询student表时添加一个班级列,内容为‘一年级’

select  列名1,列名2,列名3,‘一年级’  as   ‘年级’    from  表名; 

5.查询时合并列

select  (列名1+列名2) as  合并成的列别名   from  表名;

注意:合并列只能合并数值类型的字段

6.查询时去除重复记录

select  distinct   列名    from 表名;(去除列名中重复的)  

7.条件查询(where)

1)逻辑条件:and    or

select  * from  表名  where   条件1  and/or   条件2;

2)比较条件:>  <  >=  <=  =  <>(不等于)   between  A  and  B(等价于>=A且<=B )

3)判空条件(null   空字符串):is   null/is   not  null/==‘’(等于空字符串)/<>' '(不等于空字符串)

--null:表示没有值

--空字符串:有值,

select  * from   表名   where   列名  is null   or   列名=‘ ’;——找出列名为空的数据

select  * from   表名  where 列名  is not   null   and   列名<>' ';——找出列名不包含null且不等于空字符串的数据

4)模糊条件:like

通常使用以下替换标记:

%:表示任意个字符;

_:表示一个字符;

select  *  from   表名   where   列名   like   ‘ 张%’;——查找表中某一列中张字开头的数据

8.聚合查询

常用的聚合函数:sum()    avg()    max()     min()     count()  (注意,count()函数会排除掉空,使用count统计表的记录数,尽量使用不包含null值的字段)

select   sum(列名)as   ‘别名’     from    表名;

select   count(*)  from   表名;

9.分页查询(limit   起始行,查询几行)起始行从0开始

需求:查询第1,2条记录

select  *    from    表名   limit    0,2;

分页:只需知道当前页    当前页显示的数据条数

分页查询当前页的数据的sql:select   * from   表名   limit   (当前页-1)*当前页数据条数,当前页数据条数

10.排序查询

select  *  from 表名;——默认情况下 按照插入数据的顺序显示的数据

语法:order   by   字段    asc/desc

asc:顺序,正序。数值:递增,字母:自然顺序

desc:倒序,反序。数值:递减,字母:自然反序。

select * from  表名    order  by  要排序的列名   asc/desc;

11.分组查询(group by)group by

select  要分组的列名,count(*)  from  表名  group by  要分组的列名;将某一列分组,并计算每组的个数。

12.分组查询后筛选(having)

select  要分组的列名,count(*)  from  表名  group by  要分组的列名  having  count(*)>2;将某一列分组,并查询分成的组数大于多少的组。

上一篇 下一篇

猜你喜欢

热点阅读