sql经典笔试题

详见此处

 

表结构

sql经典笔试题_第1张图片

1.自行添加测试数据

2.查询平均成绩大于60分的同学的学号和平均成绩;

SELECT
	t1.sid 学生编号,
	AVG( t2.number ) 平均分 
FROM
	student t1
	LEFT JOIN score t2 ON t1.sid = t2.student_id 
GROUP BY
	t1.sid 
HAVING
	AVG( t2.number ) > 60

 

3.查询所有同学的学号、姓名、选课数、总成绩;

SELECT
	t1.sid "编号",
	t1.sname "姓名",
	t2.temp1 "选课数",
	t2.temp2 "总分"
FROM
	student t1,
	( SELECT student_id, COUNT( sid ) temp1, SUM( number ) temp2 FROM score GROUP BY student_id ) t2
WHERE
	t1.sid = t2.student_id;

4.查询姓“马”的老师的个数;

SELECT
	COUNT( tid ) 
FROM
	teacher 
WHERE
	tname LIKE "马%"

5.查询没学过“马云”老师课的同学的学号、姓名;

SELECT DISTINCT
	t4.*
FROM
	teacher t1
	JOIN course t2 ON t1.`tid` = t2.`teacher_id` 
	JOIN score t3 on t3.course_id = t2.cid 
	JOIN student t4 on t4.sid = t3.student_id 
WHERE
	t1.tname != '马化腾'

 

SELECT
	t1.`sid`,
	t1.`sname` 
FROM
	student t1 
WHERE
	t1.`sid` NOT IN (
SELECT
	student_id 
FROM
	score 
WHERE
	course_id IN (
SELECT
	t2.cid 
FROM
	teacher t1
	LEFT JOIN course t2 ON t1.`tid` = t2.`teacher_id` 
WHERE
	t1.tname = '马云' 
ORDER BY
	t2.`cid` 
	) 
	);

6.查询学过“001”并且也学过编号“002”课程的同学的学号、姓名;

SELECT
	t1.sid,
	t1.sname 
FROM
	(
SELECT
	t1.`student_id` sid,
	t2.`sname` sname 
FROM
	score t1
	LEFT JOIN student t2 ON t1.`student_id` = t2.`sid` 
WHERE
	course_id = 1 UNION ALL
SELECT
	t1.`student_id`,
	t2.`sname` 
FROM
	score t1
	LEFT JOIN student t2 ON t1.`student_id` = t2.`sid` 
WHERE
	course_id = 2 
	) t1 
GROUP BY
	t1.sid 
HAVING
	COUNT( * ) > 1;

 子句

SELECT
	t1.`student_id` sid,
	t2.`sname` sname 
FROM
	score t1
	LEFT JOIN student t2 ON t1.`student_id` = t2.`sid` 
WHERE
	course_id = 1 UNION ALL
SELECT
	t1.`student_id`,
	t2.`sname` 
FROM
	score t1
	LEFT JOIN student t2 ON t1.`student_id` = t2.`sid` 
WHERE
	course_id = 2 

 

7.查询课程编号“002”的成绩比课程编号“001”课程低的所有同学的学号、姓名;

SELECT
	t3.`sid`,
	t3.`sname` 
FROM
	( SELECT student_id, number FROM score WHERE course_id = 2 ) t1,
	( SELECT student_id, number FROM score WHERE course_id = 1 ) t2,
	student t3 
WHERE
	t1.student_id = t3.sid 
	AND t2.student_id = t3.sid 
	AND t1.number > t2.number;

8.查询有课程成绩小于60分的同学的学号、姓名;

SELECT DISTINCT
	t1.sid "学号",
	t1.sname "姓名" 
FROM
	student t1
	LEFT JOIN score t2 ON t2.student_id = t1.sid 
WHERE
	t2.number < 60;

9.查询没有学全所有课的同学的学号、姓名;

SELECT
	sid,
	sname 
FROM
	student 
WHERE
	sid NOT IN 
	( 
		SELECT student_id FROM score GROUP BY student_id
		HAVING count( course_id ) = 
			( SELECT count( cid ) FROM course ) 
	)

10.查询至少有一门课与学号为“001”的同学所学相同的同学的学号和姓名;

SELECT DISTINCT
	t1.student_id,
	t2.sname 
FROM
	score t1
	LEFT JOIN student t2 ON t1.student_id = t2.sid 
WHERE
	course_id IN ( SELECT course_id FROM score WHERE student_id = 2 )

 

待续、、、

 

你可能感兴趣的:(mysql,sql语句,数据库)