在本篇中,我们将深入探讨MySQL数据库中的查询语句,主要涵盖从基本的查询到复杂的条件筛选、聚合函数以及排序和分组等操作。我们首先回顾了MySQL的基础知识,然后通过一系列实例展示了如何使用SQL语句来实现各种查询需求。
1. 创建数据库和数据还原:在MySQL中,我们可以使用`CREATE DATABASE`语句创建新的数据库,如`CREATE DATABASE xskc;`,然后使用`RESTORE TABLE`或`LOAD DATA INFILE`命令恢复备份数据。
2. 查询所有学生信息:使用`SELECT * FROM students;`,这里的`*`代表所有列。
3. 查询特定列:`SELECT id, name, gender FROM students;`
4. 查询男生信息:`SELECT * FROM students WHERE gender = '男';`
5. 查询女生姓名和年龄:`SELECT name, age FROM students WHERE gender = '女';`
6. 查询年龄条件:`SELECT name, gender FROM students WHERE age < 18;`
7. 使用`BETWEEN`:`SELECT name, gender FROM students WHERE age BETWEEN 18 AND 20 AND gender = '男';`
8. 查找成绩不及格的学生:`SELECT id FROM students WHERE score < 60;`
9. 根据姓名查询:`SELECT * FROM students WHERE name LIKE '张%';`
10. 限制姓名长度:`SELECT * FROM students WHERE name LIKE '张_';`
11. 搜索包含特定字符:`SELECT * FROM students WHERE name LIKE '%敏%';`
12. 多条件组合:`SELECT * FROM students WHERE name IN ('李勇', '刘晨', '张立');`
13. 缺考学生:`SELECT id FROM students WHERE exam_id IS NULL;`
14. 统计学生人数:`SELECT COUNT(*) AS student_count FROM students;`
15. 统计男生人数:`SELECT COUNT(*) AS male_count FROM students WHERE gender = '男';`
16. 统计选课人数:`SELECT COUNT(DISTINCT student_id) AS course_participation FROM enrollments;`
17. 查询课程最高成绩:`SELECT MAX(score) AS max_score FROM scores WHERE course_id = 1;`
18. 计算课程成绩统计:`SELECT MIN(score), MAX(score), SUM(score), AVG(score) FROM scores WHERE course_id = 1;`
19. 学生所有课程成绩统计:`SELECT min_score, max_score, sum_score, avg_score FROM (SELECT MIN(score) AS min_score, MAX(score) AS max_score, SUM(score) AS sum_score, AVG(score) AS avg_score FROM scores WHERE student_id = '201215121' GROUP BY course_id) AS score_stats;`
20. 查询前3名学生:`SELECT name, gender, age FROM students ORDER BY age LIMIT 3;`
21. 查询最小年龄的3名学生:`SELECT name, gender, age FROM students ORDER BY age LIMIT 3;`
22. 按成绩降序排列:`SELECT student_id, score FROM scores WHERE course_id = 1 ORDER BY score DESC;`
23. 统计各门课选课人数:`SELECT course_id, COUNT(DISTINCT student_id) AS enrollment_count FROM enrollments GROUP BY course_id;`
24. 输出选课人数不足3人的课程:`SELECT course_id FROM enrollments GROUP BY course_id HAVING COUNT(DISTINCT student_id) < 3;`
25. 统计每名学生选修课程数:`SELECT student_id, COUNT(DISTINCT course_id) AS course_count FROM enrollments GROUP BY student_id;`
26. 选修3门以上课程的学生:`SELECT student_id FROM enrollments GROUP BY student_id HAVING COUNT(DISTINCT course_id) >= 3;`
这些例子覆盖了MySQL查询语句的基本用法,包括选择字段、条件过滤、排序、分组和聚合函数的使用,可以帮助读者更好地理解和掌握SQL查询技巧。在实际应用中,根据具体需求调整这些语句,可以解决大部分数据库查询问题。
可以使用以下 SQL 语句查询选修课程的人数:
SELECT COUNT(*) FROM course_selection WHERE course_name = '选修课程名称';
其中,course_selection 是选课表的表名,course_name 是选修课程的名称。