天天看点

【MySQL数据库】 数据库的基本查询 DQL数据库的基本查询 DQL

【MySQL数据库】 数据库的基本查询 DQL数据库的基本查询 DQL

目录

数据库的基本查询 DQL

简单查询

聚合查询

分组查询

排序查询

分页查询

数据库的基本查询 DQL

简单查询

--查询所有的商品                     
select * from 表名;

--查询商品名和商品价格                
select 列名1,列名2 from 表名;

--别名查询使用关键字as(as可以省略)    
select * from 表名 as 别名;
select 列名 as 别名 from 表名;

--去掉重复值(distinct)               
select distinct 列名 from 表名;

--查询结果是表达式(运算查询)          
select 列名1,列名2(运算)from 表名;
select pname,price+10 from product;

--条件查询:                        
select 列名1,列名2...from 表名 where 条件,条件2...
           

聚合查询

除count外其他聚合函数忽略对Null的存在(即视该记录不存在)

--查询商品的总条数                  
select count(*) from product;

--查询价格大于200商品的总条数        
select count(*) from product where price > 200;

--查询分类为'c001'的所有商品的总和   
select sum(price) from product where category_id = 'c001';

--查询商品的最大价格                
select max(price) from product;

--查询商品的最小价格                
select min(price) from product;

--查询分类为'c002'所有商品的平均价格 
select avg(price) from product where category_id = 'c002';
           

分组查询

格式 

 select 字段1,字段2,...from 表名 group by 分组字段 having 分组条件

select category_id ,count(*) from product group by category_id ;

select category_id ,count(*) from product group by category_id having count(*) > 1;
           

注意:在使用分组查询时应该使用 having+条件语句

排序查询

格式:select 字段名1,字段名2,...from 表名order by 字段名1 [asc|desc],字段名2[asc|desc]…

order by 子句来设定你想按哪个字段哪种方式来进行排序

1.asc代表升序,desc代表降序,如果不写默认升序

2.order by用于子句中可以支持单个字段,多个字段,表达式,函数,别名

3.order by子句,放在查询语句的最后面。LIMIT子句除外

分页查询

        分页查询在项目开发中常见,由于数据量很大,显示屏长度有限,因此对数据需要采取分页显示方式。例如数据共有30条,每页显示5条,第一页显示1-5条,第二页显示6-10条。 

-- 方式1-显示前n条

select 字段1,字段2... from 表明 limit n

-- 方式2-分页显示

select 字段1,字段2... from 表明 limit m,n

m: 整数,表示从第几条索引开始,计算方式 (当前页-1)*每页显示条数

n: 整数,表示查询多少条数据

-- 查询product表的前5条记录
select * from product limit 5

-- 从第4条开始显示,显示5条
select * from product limit 3,5