-
去重 distinct 關鍵字
eg. :select distinct university from user_profile
-
返回行數限制: limit關鍵字
eg. :select device_id from user_profile limit 2
-
返回列重命名:as 關鍵字
eg.:select device_id as user_infos_example from user_profile limit 2
-
指定關鍵字排序:order by 關鍵字(ASC升序,DESC降序):
eg:select device_id,age from user_profile order by age asc
-
統計總數 + 模糊條件篩選: count + where + like
eg.:
selectcount(distinct device_id) as did_cnt,count(question_id) as question_cnt
from question_practice_detail
where date like "2021-08%"
-
判斷非空: is not null
eg.:select device_id,gender,age,university from user_profile where age is not null
-
多條件判斷 : where in / not in
eg.:
select device_id, gender, age ,university, gpafrom user_profile where university in ('北京大學','復旦大學','山東大學')
- 正則表達式:使用regexp 進行正則匹配
正則表達式匹配的字符類:
.:匹配任意單個字符。
^:匹配字符串的開始。
$:匹配字符串的結束。
*****:匹配零個或多個前面的元素。
+:匹配一個或多個前面的元素。
?:匹配零個或一個前面的元素。
[abc]:匹配字符集中的任意一個字符。
[^abc]:匹配除了字符集中的任意一個字符以外的字符。
[a-z]:匹配范圍內的任意一個小寫字母。
[0-9]:匹配一個數字字符。
\w:匹配一個字母數字字符(包括下劃線)。
\s:匹配一個空白字符。
eg.:
select id,name,phone_numberfrom contactswhere phone_number regexp '^[1-9][0-9]{2}-?[0-9]{4}-?[0-9]{4}$'
-
取最大值 : max
eg.:select max(gpa) as gpa from user_profile where university = '復旦大學'
-
規定小數點位數及統計平均值: round + avg
ROUND 函數用于把數值字段舍入為指定的小數位數。
用法為:SELECT ROUND(column_name,decimals) FROM table_name
eg.:
select count(gender) as male_num,round(avg(gpa),1) as avg_gpa
from user_profile
where gender = 'male'
- 分組查詢: group by
eg.
select gender,university,count(device_id) as user_num, round(avg(active_days_within_30),1) as avg_active_day,round(avg(question_cnt),1) as avg_question_cntfrom user_profilegroup by gender,universityorder by gender asc,university asc
注意: 由于group by后的輸出不可預估,因此在筆試時可能會出現僅使用group by 無法通過測試用例的情況,此時需按用例示范追加 order by !!!
- 分組后條件過濾: having
eg.:
select university,round(avg(question_cnt),1) as avg_question_cnt,round(avg(answer_cnt),1) as avg_answer_cnt
from user_profile group by universityhaving avg_question_cnt < 5 or avg_answer_cnt < 20
- 多表查詢- 內連接:inner join ,注意應指定列。
eg.:
select q.device_id,q.question_id,q.result from question_practice_detail as qinner join user_profile as upon q.device_id = up.device_id and up.university = '浙江大學'