1. 程式人生 > >MySQL面試試題與答案

MySQL面試試題與答案

本次試題設計兩個表:student、exam

           student表

          exam表

 

一、寫一條SQL語句,按學號排序輸出數學成績

SELECT s.sno sno,score
FROM exam e,student s
WHERE e.`subject` = '數學' AND e.name = s.name
GROUP BY s.sno

 

二、寫一條SQL語句,按學號排序,輸出:學號,姓名,總分,平均分

SELECT sno,s.`name`,SUM(score) ss,AVG(score) gg
FROM exam e,student s
WHERE e.`name` = s.`name`
GROUP BY `name`
ORDER BY ss

 

三、寫一條SQL語句,查詢出數學考試成績最高的學生學號和姓名

SELECT sno,exam.name name,score
FROM exam,student
WHERE (exam.`subject` = '數學') AND (exam.name = student.name)
ORDER BY
exam.score DESC LIMIT 0,1;

 

四、寫一條SQL語句,查詢出每門課都大於80分的學生姓名

方法一:ALL()函式

思路:查找出每個人所有科目是否都大於80

SELECT DISTINCT NAME 
FROM exam a
WHERE 80 < ALL(SELECT score 
               FROM exam e
               WHERE e.name = a.name );

 

方法二:not exists 欄位

思路:排除掉存在學科分數低於80的學生,剩下的就是所有學科分數都大於80的學生

SELECT DISTINCT NAME
FROM exam a
WHERE NOT EXISTS (SELECT name
                  FROM exam e 
                  WHERE e.name = a.name AND e.score < 80 );

 

方法三:not in 欄位

思路:同上

SELECT DISTINCT NAME 
FROM exam 
WHERE NAME NOT IN (SELECT  NAME 
                   FROM exam
                   WHERE score<=80)

 

方法四:having 欄位

思路:過濾出學科中最低分數大於80的學生

SELECT name
FROM exam
GROUP BY name
HAVING min(score) > 80

 

五、張三退學後,請寫相關的SQL語句,注意嚴謹

DELETE
FROM exam
WHERE name = '張三';
DELETE
FROM student
WHERE name = '張三';

 

六、你會對該表哪些欄位做索引

id - 唯一索引

七、這兩個表的設計,有哪些可以改進的地方

student表中sno欄位可以改成‘studentID’,更語義化,

exam表中取消name欄位及該列資料,改用student中sno學號欄位代替,更易於檢索