經典資料庫sql練習
阿新 • • 發佈:2019-02-19
經典練習:
四張表:學生表 、老師表、課程表、成績表
學生表 :
CREATE TABLE `student` (
`student_number` int(10) NOT NULL AUTO_INCREMENT COMMENT '學生學號',
`student_name` varchar(50) NOT NULL COMMENT '學生姓名',
`student_age` int(10) NOT NULL COMMENT '學生年齡',
`student_sex` varchar(10) NOT NULL COMMENT '學生性別',
PRIMARY KEY (`student_number` )
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
老師表:
CREATE TABLE `teacher` (
`teacher_number` int(10) NOT NULL COMMENT '教師編號',
`teacher_name` varchar(10) NOT NULL COMMENT '教師姓名',
PRIMARY KEY (`teacher_number`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
課程表:
CREATE TABLE `course` (
`course_number` int(10) NOT NULL COMMENT '課程編號',
`course_name` varchar(10) NOT NULL COMMENT '課程名稱',
`teacher_number` varchar(10) NOT NULL COMMENT '教師編號',
PRIMARY KEY (`course_number`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
成績表:
CREATE TABLE `student_score` (
`student_number` int(10) NOT NULL COMMENT '學生學號',
`course_number` int(10) NOT NULL COMMENT '課程編號',
`score` int(10) NOT NULL COMMENT '成績',
PRIMARY KEY (`student_number`,`course_number`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
裡面資料自己新增!
sql練習:
1、查詢“1”課程比“2”課程成績高的所有學生的學號;
select a.student_number from (select student_number,score from student_score where course_number='1') a,(select student_number,score from student_score where course_number='2') b where a.score>b.score and a.student_number=b.student_number;
2、查詢平均成績大於60分的同學的學號和平均成績;
SELECT student_number,AVG(score) FROM student_score GROUP BY student_number HAVING AVG(score) > 60
3、查詢所有同學的學號、姓名、選課數、總成績;
SELECT a.student_number,a.student_name,count(c.course_number),sum(score) FROM student a LEFT OUTER JOIN student_score c ON a.student_number=c.student_number GROUP BY a.student_number
4、查詢姓“李”的老師的個數;
SELECT COUNT(t.teacher_name) from teacher t where teacher_name LIKE '李%'
5、查詢沒學過 “張三” 老師課的同學的學號、姓名
SELECT
a.student_number,
a.student_name
FROM
student a
WHERE
a.student_number NOT IN(
SELECT DISTINCT
(b.student_number)
FROM
student_score b,
course c,
teacher d
WHERE
b.course_number = c.course_number
AND d.teacher_number = c.teacher_number
AND d.teacher_name = '張三'
)
6、查詢學過“001”並且也學過編號“002”課程的同學的學號、姓名;