MYSQL教程:查詢篇



-- 查詢
-- 1.要求求出每個學生對應的老師。
 create view wr_v_teach
 as 
  SELECT a.`name`,c.teachername
  from wr_t_students a, wr_t_class b,wr_t_teacher c
where a.classid=b.id
and b.teacherid=c.id
;
-- java優化建議:儘量多使用視圖(VIEW)來查詢.
-- VIEW就是快捷方式
  create view wr_v_students 
 as 
SELECT a.id,a.age,a.birth,a.classid,a.creditcard,a.major,a.`name`,a.photoid,a.telephone,a.univercity,
    (case when a.sex=1 then '男' else '女' end) sex
  from wr_t_students a
;

-- 2.取students表的前5條記錄(不用top,而用Limit)
  SELECT  *
  from wr_t_students a limit 1,5  -- limit n 表示取前n條   limit m,n表示取從第m條(不包括m)開始取n條  分頁
;
-- 3.取students表有幾個班級的學生
   SELECT  DISTINCT a.classid  -- 祛除重複的關鍵字:distinct
  from wr_t_students a
;

-- 4.取出photoid爲空的數據
   SELECT a.id,a.age,a.birth,a.classid,a.creditcard,a.major,a.`name`,a.photoid,a.telephone,a.univercity,
    (case when a.sex=1 then '男' else '女' end) sex
  from wr_t_students a
where a.photoid is null -- a='null' =''
;
-- 5.讓性別=1顯示男,=0顯示女
  SELECT a.id,a.age,a.birth,a.classid,a.creditcard,a.major,a.`name`,a.photoid,a.telephone,a.univercity,
    (case when a.sex=1 then '男'   -- 1.case xx when xx1    (不推薦: ) 2. case when xx=xx1 /xx is null
          else '女' 
          end) sex
  from wr_t_students a
 ;
-- 6.計算每名老師分別都有多少學生
-- 聚合函數:count,sum,max,min,avarage
-- 第一種取交集查詢
   SELECT c.teachername,count(a.`name`)   -- 計算有多少條數據 :count
  from wr_t_students a, wr_t_class b,wr_t_teacher c
where a.classid=b.id
and b.teacherid=c.id
GROUP BY c.teachername
;
-- 第二種方法view
select a.teachername,count(*)
from wr_v_teach a
GROUP BY a.teachername
 ;
-- 第三種方法嵌套查詢
SELECT d.teachername,count(*)
from  (SELECT a.`name`,c.teachername
  from wr_t_students a, wr_t_class b,wr_t_teacher c
where a.classid=b.id
and b.teacherid=c.id) d
GROUP BY d.teachername
;
-- 7.按照年齡,性別從小到大排序
SELECT *
from wr_t_students a
ORDER BY a.sex,a.age 
 ;
-- 8.取左、取右
SELECT a.creditcard,right(a.creditcard,2),left(right(a.creditcard,2),1)
from wr_v_students a
;
-- 9.去除空格  trim
SELECT *
from wr_v_students a
where trim(a.univercity)='南京郵電大學'
or a.univercity='南郵'
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章