經典sql面試題

表結構

Student(s_id, sname, sage, ssex) 學生表
Course(c_id, cname, t_id)課程表
SC(s_id, c_id, score)成績表
Teacher(t_id,tname)教師表

建表語句

CREATE TABLE `student` (
  `s_id` int(11) DEFAULT NULL,
  `sname` varchar(32) DEFAULT NULL,
  `sage` int(11) DEFAULT NULL,
  `ssex` varchar(8) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE `course` (
  `c_id` int(11) DEFAULT NULL,
  `cname` varchar(32) DEFAULT NULL,
  `t_id` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE `sc` (
  `s_id` int(11) DEFAULT NULL,
  `c_id` int(11) DEFAULT NULL,
  `score` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE `teacher` (
  `t_id` int(11) DEFAULT NULL,
  `tname` varchar(16) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

面試問題

1. select的結果可以當做一個表

查詢“001”課程比“002”課程成績高的所有學生的學號;

select a.s_id from (select s_id,score from SC where c_id='001') a,(select s_id,score 
  from SC where c_id='002') b 
  where a.score>b.score and a.s_id=b.s_id;

2. 聚集函數和groupby一起出現,where不能連用

查詢平均成績大於60分的同學的學號和平均成績;

    select s_id,avg(score) 
    from sc 
    group by s_id having avg(score) >60; 

3. 連接查詢+groupby

查詢所有同學的學號、姓名、選課數、總成績

select s.s_id, s.sname, count(c.c_id), sum(c.score)
from student s, sc c where s.s_id = c.s_id
group by s.s_id;

4. 子查詢 in 、not in

查詢沒學過“葉平”老師課的同學的學號、姓名;

select Student.S#,Student.Sname 
from Student  
where s_id not in (
select distinct( SC.S_id) from SC,Course,Teacher 
where  SC.c_id=Course.c_id and 
Teacher.t_id=Course.t_id and Teacher.Tname='葉平'); 

查詢至少有一門課與學號爲“1001”的同學所學相同的同學的學號和姓名;

select distinct s_ic,sname from Student,SC where Student.s_id=SC.s_id and SC.c_id in (select c_id from SC where s_id='1001'); 

5. and 不能連接同一個字段

查詢學過1並且也學過編號2課程的同學的學號、姓名;
正確寫法:

select s_id from sc where score = 90 and c_id in (1,2);

錯誤寫法:

select s_id from sc where score = 90 and c_id = 1 and c_id = 2;

6. 查詢同名同性學生名單,並統計同名人數

select sname,count(*) from Student group by sname having  count(*)>1;

7. Order by 多個字段

例如order by id, score desc
首先會按照id降序排列,當id相同時,再按score降序排列

查詢每門課程的平均成績,結果按平均成績升序排列,平均成績相同時,按課程號降序排列

select c_id, avg(score) from sc GROUP BY c_id order by avg(score) , c_id desc;

8. group by多個字段

例如group by s_id, c_id
表示屬於s_id, 又屬於c_id的,例如屬於1號學生的,又屬於2號課程的

工作流程:
首先按照s_id分組,分組的結果再用c_id來分組

查詢平均成績大於85的所有學生的姓名和平均成績;

select s.s_id, s.sname, avg(c.score) from student s, sc c
where s.s_id = c.s_id group by s.sname , s.sage having avg(score) > 80;

因爲學生可能同名,所以group by s.sname , s.sage的作用就是,先按姓名分組,要是有重複的姓名,再按照性別分組。

9. MySQL不支持top,用limit,而且limit不能用於子查詢

查詢每門功成績最好的前兩名
錯誤寫法:

select s.s_id, s.sname , c.score from student s, sc c 
where s.s_id = c.s_id and score in(
select score from sc GROUP BY s_id order by score desc limit 2);

正確寫法:

select s.s_id, s.sname , c.score from student s, sc c 
where s.s_id = c.s_id and score in(
select score from sc GROUP BY s_id order by score desc)
limit 2;
發佈了177 篇原創文章 · 獲贊 405 · 訪問量 94萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章