
目錄
資料庫的基本查詢 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