初級軟件測試工程師之必備SQL語句基礎

作爲一個軟件測試工程師,我們在測試過程中往往需要對數據庫數據進行操作,但是我們的操作大多以查詢居多,有時會涉及到新增,修改,刪除等操作,所以我們其實並不需要對數據庫的操作有特別深入的瞭解,以下是我在工作過程中整理的比較常用的SQL語句。

1.插入表數據:
insert into 表名1 (字段1,字段2) values(字段1值,字段2值);
 
2.刪除表數據:
delete:delete from 表名1 where 範圍(刪除表內符合條件的內容)
delete from 表名1(清空數據表內容,不釋放空間,即:下次插入表數據,id依然接着刪除數據的id繼續增加)
truncate:truncate table 表名1(清空表數據,釋放空間,即:下次插入表數據,id從1重新開始)
drop:drop table 表名1(整張表被刪除,要使用該表必須重新建)
 
3.修改表數據:
update 表名1 set 字段名 = ‘新值’ where 範圍
 
4.查詢表數據:
 
查詢數據:select * from table1 where 範圍
總數:select count (*) from table1 where 範圍
select count (distinct(字段1) from table1 where 範圍(distinct可去重)
求和:select sum (字段1) from table1 where 範圍
平均:select avg (字段1) from table1 where 範圍
最大:select max (字段1) from table1 where 範圍
最小:select min (字段1) from table1 where 範圍
排序:select * from table1 where 範圍 order by 排序字段名 desc(desc逆序排序。默認是正序排序asc)

 

 

5.複雜查詢:
嵌套查詢:多個查詢語句嵌套在一起查詢,一般嵌套的查詢語句放在where 或 having 的後面
例:
select * from table1 where status in(select status from table2)
 
多表連接查詢:

table1:

 

id username
1 張三
2 李四
3 王二
table2:

 

id job
1 teacher
2 student
4 worker
 
(1)內聯查詢(inner join……on……)
select * from table1 a inner join table2 b on a.id=b.id
查詢結果:
id
username
id
job
1
張三
1
teacher
2
李四
2
student
(2)左外聯(left outer join……on……)
select * from table1 a left outer join table2 b on a.id=b.id
查詢結果:
id
username
id
job
1
張三
1
teacher
2
李四
2
student
3
王二
null
null
(3)右外聯(right outer join……on……)
select * from table1 a right outer join table2 b on a.id=b.id
id
username
id
job
1
張三
1
teacher
2
李四
2
student
null
null
4
worker
(4)全外聯(full outer join……on……)
select * from table1 a full outer join table2 b on a.id=b.id
id
username
id
job
1
張三
1
teacher
2
李四
2
student
3
王二
null
null
null
null
4
worker
6.group by分組
根據某一個或多個列表字段進行分組統計。
table1:
id
name
course
score
1
張一
Chinese
80
2
張二
Chinese
60
3
張三
math
65
4
張三
Chinese
70
5
張一
math
90
 
查詢每個用戶的最高成績:
select name,max(score) as max_score from table1 group by name
查詢結果:先按用戶名分組,再在每個組中查詢找到最高分數
id
name
max_score
1
張一
90
2
張二
60
3
張三
70
 
查詢全班每科課程平均分
select course,avg(score) as avg_score from table1 group by course
查詢結果:先按課程分組,再在每個組中查詢找到平均分數
id
course
avg_score
1
chinese
70
2
math
77.5
 
having的用法:同where用法,having與group by連用。where是篩選單個記錄,having是篩選分組記錄(先分組,後篩選)

 

作爲一個初中級測試人員,一般情況下擁有以上的數據庫知識就可以滿足大部分的測試需要了。

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章