student表中内容如下:
/*
limit分頁
格式1:limit 數字;
數字表示從頭開始顯示多少行
格式2:limit 數字1,數字2;
數字1表示開始位置
數字2表示顯示行數
*/
select * from student limit 5;
select * from student limit 2,3;
/*
distinct 去重
格式:distinct 字段1,字段2...字段n
例如:select distinct name,age from student; 以name和age進行去重
注意:distinct以之後所有字段進行去重
去重時,distinct必須寫在字段最前面
*/
select distinct sex from student;
/*
内置函數
聚合函數
count():統計某個字段有多少行資料(累加)
例如:select count(name) from student;擷取student中name字段有多少資料
例如:select count(*) from student; 擷取student中有多少行資料
例如:select count(1) from student; 擷取student中有多少行資料
可以求多字段的行數
例如:select count(name and age) from student;
注意:求字段有多少行資料時,如果有的資料為null,那麼為null的資料不參與計算
求多字段按最大的結果進行顯示
sum():求和
例如:select sum(age) from student;
注意:字段類型為非int時,結果為0
avg():求平均數
min/max:最小值/最大值
注意:字段屬性可以為varchar,按照自然排序
拼接
concat
格式:concat(str1,str2,...);
例如:select concat(name,',',age) from student;
concat_ws
格式:concat_ws(separator,str1,str2,...);
例如:select concat_ws(',',name,age) from student;
差別:concat需要手動進行分割
concat_ws直接指定分隔符
*/
select count(name) from student; #列出name字段中有多少條(null不算)資料
select count(*) from student; #如果沒有指定count中具體的列,那就是列出全部資料的行數
select sum(age) from student; #sum函數求(int)總和,如果是其他類型會轉成int,varchar轉成為0
select avg(age) from student; #avg函數求平均數
select max(age),min(age) from student; #max(列名)、min(列名)表示這一列最大值、最小值
select max(name),min(name) from student; #如果max、min裡面是varchar,則按照自然排序
select CONCAT(name,'_',age,'_',sex) as 姓名_年齡_性别 from student; #concat 需手動進行分割,拼接字元串
select CONCAT_WS('_',name,age,sex) as 姓名_年齡_性别 from student; #concat_ws 直接指定分隔符,拼接字元串