1. 程式人生 > >MySQL資料庫操作(二)——DQL

MySQL資料庫操作(二)——DQL

DQL

關鍵字:select、from、where、group by、having、roder by

基本查詢

  查詢所有:select * from 表名;

select * from t_stu;

  查詢部分列select 列名,...列名 from 表名;

select stu_num,stu_name from t_stu;

  查詢去除完全重複的列select distinct * from 表名;

select distinct * from t_stu;
select distinct stu_age from t_stu;

  也可以查詢同時做加、減、乘、除運算操作

//把查詢出來的年齡都乘以2倍。
select stu_age*2 from t_stu;
//如果查出來的年齡為null,就設定為29
select ifnull(stu_age,29) from t_stu;

  做連線字串操作:CONCAT

//把名字和年齡拼接起來
select CONCAT(stu_name,stu_age) from t_stu;

select CONCAT('我的名字是:',stu_name,',我今年',stu_age,'歲') from t_stu;

  給列起別名:as

select stu_age as 年齡 from t_stu;
select stu_age as 年齡,stu_name as 姓名 from t_stu;
select CONCAT(stu_name,stu_age) as 描述 from t_stu;

條件查詢

  跟前面一篇講的更新,刪除裡面設定條件的方法是一樣的。where後面跟條件

//查詢年齡大於等於20的學生
select * from t_stu where stu_age>=20;
//查詢年齡在15到25歲之間的學生
select * from t_stu where stu_age between 15 and 25;
//查詢名字叫zhangsan,lisi,wangwu.zhaoliu的學生
select * from t_stu where stu_name in('zhangsan','lisi','wangwu','zhangliu');

  模糊查詢like

//一個字加一個下劃線,兩個字就是兩個下劃線
//查詢名字中張開頭,並且是兩個字的學生.
select * from t_stu where stu_name like '張_';
//查詢名字是三個字的學生
select * from t_stu where stu_name like '___';

//百分號%匹配0~N個字元
//查詢名字中以雷結尾的學生
select * from t_stu where stu_name like '%雷';
//查詢名字中包含曉的學生
select * from t_stu where stu_name like '%曉%';

排序 order by

// desc:降序,asc:升序
//按學生年齡升序排列
select * from t_stu ORDER BY stu_age ASC;
//按學生年齡降序排列
select * from t_stu ORDER BY stu_age DESC;
//年齡相同的時候,按名字降序排列。可以無限新增排序條件
select * from t_stu ORDER BY stu_age ASC,stu_name DESC;

聚合函式(縱向查詢)

計數count

//只要不為null,就+1
select count(*) from t_stu;
select count(stu_age) from t_stu;

計算和sum

//計算學生年齡加起來的總數
select sum(stu_age) from t_stu;

最大值max,最小值min

//查詢年齡中最大的
select max(stu_age) from t_stu;
//查詢年齡中最小的
select min(stu_age) from t_stu;

平均值avg

select avg(stu_age) from t_stu;

分組查詢group by

寫法:select 條件,聚合函式,...,聚合函式 from 表名 group by 條件;

分組查詢必須都是聚合函式,並且,上面兩個位置的條件必須相同

//按老師分組查詢,每組老師名下的學生個數
select stu_teacher,count(*) from t_stu group by stu_teacher;

//分組前條件,不滿足條件的沒有參加分組
//按老師分組查詢,查詢每組老師名下年齡大於20歲的學生的個數
select stu_teacher,count(*) from t_stu where stu_age>20 group by stu_teacher;

//having 分組後條件
//按老師分組查詢,查詢老師名下年齡大於20歲的學生,並且剔除學生個數小於5個的老師
select stu_teacher,count(*) from t_stu where stu_age>20 group by stu_teacher having count(*)<5;

limit(MySQL特有的)

//從下標0開始,往後查詢5條資料
select * from t_stu limit 0,5;

//分頁查詢,比方說如果你要查第N頁的資料,每頁資料M條
//(當前頁-1)*每頁的資料數
select * from t_stu limit (N-1)*M,M;