DML
添加數據:
insert into 表名(列名1,列名2,...列名n) values (值1,值2,...值n);
-- 列名和值要一一對應。
-- 如果知道表名後,不定義列名,則默認給所有的列添加值
insert into 表名 values(值1,值2...值n);
-- 除了數據類型,其他類型需要使用引號(單雙引號都可以)引起來
刪除數據:
delete from 表名 [where條件];
--刪除表,在重新創建一個一模一樣的
truncate table 表名;
-- 注意如果不加條件會修改所有列
修改數據:
update 表名 set 列名1 = 值1,列名2 = 值2,...[where 條件];
select * from 表名;
排序查詢
/*語法:order by 子句
-- order by 排序字段1 排序方式1,排序字段2 排序方式2....
-- eg */
select * from student order by math;-- 默認升序排序
/*
-- ASC:升序,默認
-- DESC:降序
-- 注意:如果有多個排序條件,則當前面的條件值一樣時,纔會判斷第二條件。
-- eg:按照數學成績排名,如果數學一樣,按照英語來排序
*/
select * from student order by math ASC,english DESC;
聚合函數:將一列數據作爲整體,進行縱向的計算
- count:計算個數。一般選擇非空列如:主鍵;count(*);
- max
- min
- sum
- avg
select count(english) from student;
-- 注意:聚合函數計算時排除null值
select count(IFNULL(english,0)) from student;
select count(*) from student;
select MAX(math) from student;
select Min(math) from student;
select sum(english) from student;
select avg(math) from student;
分組查詢:
1、語法:group by 分組字段;
2、注意:
- 分組之後查詢的字段:分組字段,聚合函數
- where 和having的區別?
1.where在分組之前進行限定,如果不滿足條件的元組不參與分組。having在分組之後進行限定,如果不滿足結果元組,則不會被查詢出來。
2.where後不可以跟聚合函數,having可以進行聚合函數的判斷
--按性別分組。分別查詢男、女同學平均分
select sex,avg(math) from student group by sex;
--按性別分組。分別查詢男、女同學平均分,人數
select sex,avg(math),count(id) from student group by sex;
--按性別分組。分別查詢男、女同學平均分,人數 要求:分數低於70分的人,不參與分組
select sex,avg(math),count(id) from student where math > 70 group by sex;
--按性別分組。分別查詢男、女同學平均分,人數 要求:分數低於70分的人,不參與分組
select sex,avg(math),count(id) from student where math > 70 group by sex having count(id) >2;
select sex,avg(math),count(id) 人數 from student where math > 70 group by sex having 人數 >2;
分頁查詢
語法:limit開始索引,每頁查詢的條數;
公式:開始的索引 = (當前的頁碼 - 1)* 每頁顯示的條數
limit 是mysql的方言
select * from student limit 0,3;
select * from student limit 3,3;
select * from student limit 6,3;