一.order by 列名

例如:

1.//按id排序,默认是按升序排列的,

select * from table order by id;等同于select * from table order by id ASC;

2.按降序排列:

select * from table order by desc;

3.按多个字段排序:

例如:select * from table order by id,name;

二.where 子句操作符

 

 

三.范围值检查:

关键字:between    and

例如:

select * from table where id between 1 and 3;

 

四.控制检查

关键字:IS NULL

例如://查出所有name字段为null的值

select * from table where name is null;

 

5.组合where子句

5.1. AND操作符

例如://查找id等于1并且名字为lisi的人

select * from table where id=1 and name='lisi';

5.2.OR操作符

例如://查找id=2或者名字为lisi的用户

select * from table where id=2 OR name='lisi';

5.3.AND与OR关键字组合

示例://ADN在计算中的优先级高于OR,如果不加()括号会先算AND部分

select * from table where (id=2 OR id=3) AND name='lisi';

5.4.IN操作符--用来指定条件范围的

例如://查询id为1,3,5的人,并按name进行降序排列

select * from table where id IN (1,3,5) order by name desc;

5.5.NOT操作符--不等于

例如://id不等于1

select * from table where not id=1 order by name desc;

 

6.用通配符进行过滤

6.1.like通配符

6.1.1.%通配符

示例:1://模糊查询,查询name字段里以li开头的所有信息

select * from table where name like 'li%';

示例2:查询name字段里以si结尾的所有信息:

select * from table where name like '%si';

示例3:查询name字段里以'x'开头和以'y'结尾的所有信息

select * from table where name like 'x%y';

6.1.2.下划线通配符"_"

与%号作用一样,但是下划线通配符只能匹配单个字符,而不能匹配多个字符,下划线'_'可以在任何位置

示例:

select * from test where name like 'lis_';

6.1.3.方括号"[]"通配符

示例:

select * from table where name like '[zlw]%' order by name desc;

7.通配符的使用技巧

SQL算数操作符:

8.数据库函数:

8.1.文本函数列表

8.1.1小写字母转换为大写字母的函数:upper();

用法:

SELECT NAME,UPPER(NAME) AS NAME_UPCASE FROM USER ORDER BY NAME;

 

8.2.日期处理函数:

 

9.聚集函数

 

9.1.AVG()函数:

用法1:select AVG(price) AS avg_price from orders;

用法2:select AVG(price) AS avg_price from orders where id =100;

9.2.COUNT()函数:

用法1:select count(*) from orders;//对所有列进行计数

用法2:mysql> select count(price) as price_num from orders;//对某一个字段进行计数

9.3.MAX()函数:

用法1:select max(price) as price_max from orders;//找出价格最贵的商品

9.4.min()函数:

用法:select min(price) as price_min from orders;//找出价格最便宜的商品

9.5.sum()求和函数:

用法1:

select sum(pro_quantity) as quantity_sun from orders;//求商品的数量之和

用法2:select sum(pro_quantity*price) as total_price from orders;//数量乘以价格之和

去重参数:

distinct

用法:

select  distinct 列名 from table;

 

9.6.组合聚合函数:

用法:

select count(*) as num,max(price) as max_price,min(price) as min_price,avg(price) as avg_price from orders;

 

10.数据分组:

10.1示例:

mysql> select vend_id,sum(num_prods) as sum_prods from products group by vend_id;

 

group by子句使用注意事项

10.2.过滤分组:

HAVING子句:

示例:

mysql> select vend_id,count(*) as orders from products group by vend_id having c
ount(*) >=3;

10.3.select子句顺序:

11.子查询