表結構以下:函數
做者表:(做者編號,做者姓名,性別,年齡,居住城市,聯繫電話,銷量,最新出版日期);學習
authors(authorId,authorName,sex,age,city,telephone,sales,isbn);spa
1)查詢姓王的做者信息排序
select * from authors where authorName like'高%';ci
注意:like關鍵詞前面要有whereit
2)查詢聯繫電話第三位爲八、9並以888結尾的做者信息date
分析:得到聯繫電話的第三位,這裏要用到函數截取,substr();以888結尾用like便可;也能夠用substr()函數,substr(telephone,length(telephone)-2,3)='888';方法3,用like '_________888',一個_表明匹配一個數字select
截取函數的格式:substr(字段A,截取開始的位置, 截取字符個數 )分頁
語句:方法
select * from authors where substr(telephone,3,1) in (8,9) and telephone like'%888';
或者:select * from author where substr(telephone,3,1) in (8,9) and substr(telephone,length(telephone)-2,3)='888';
3)查詢年齡在20-50之間的男性做者信息
分析:年齡在20-50之間,這裏要用到關鍵詞between
語句:
select * from authors where age between 20 and 50 and sex='男';
4)查詢顯示做者姓名的第二個字符
分析:獲取姓名的第二個字符方法,substr(name,2,1)
語句:
select substr(authorName,2,1) from authors;
5)查詢顯示做者姓名的長度
分析:用到函數,length()
語句:
select authorName,length(authorName) from authors;
6)查詢顯示最年經的5位做者的平均銷量
分析:先把做者表按年齡從小到大排序,而後取前5位數據,對這5位數據算出平均值
語句:
錯誤寫法:
select avg(sales) from authors order by age asc limit 0,5;
分析:這裏所算出的是全部銷量的平均值
正確寫法:
select avg(sales) from (select sales from authors order by age asc limit 0,5) s1;
7)查詢顯示做者的姓名,出生年份,銷量,並按銷量降序排列
分析:信息表中沒有出生年份,須要本身算出,用獲取年份的函數year()-年齡便可;如何獲取年份,先獲取當前時間,而後提取年份便可,year(curdate());
語句:
select authorName,year(curdate())-age as '出生年份', sales from authors order by sales desc;
8)查詢顯示最新出版日期在今年前半年的做者信息
分析:先判斷是否在今年,而後從最新出版日期獲取月份,判斷是否小於7便可
語句:
select * from authors where year(isbn)=year(curdate()) and month(isbn)<7;
總結:
從這個題目中,所學習到的函數有:
一、截取函數substr(字段名,截取的開始位置,截取的長度),
二、獲取字段的長度函數,length(字段名)
三、截取範圍以內值的關鍵字,between 範圍1 and 範圍2
四、分頁函數,limit m,n:從m行開始,每頁取n條;
五、獲取當前時間的年份,月份,天數的函數分別爲:year(curdate()),month(curdate()),day(curdate());