MYSQL语句 每个学生可以选一门或多门课程 求至少同时选修数学和英语的学生的学号
时间: 2024-10-28 12:12:50 浏览: 35
在MySQL中,你可以使用`JOIN`和`GROUP BY`以及`HAVING`语句来查询至少同时选修数学和英语的学生的学号。假设我们有两个表,一个是`students`,包含字段`student_id`(学号);另一个是`courses`,包含字段`student_id`和`course_name`。
这里是一个可能的SQL查询示例:
```sql
SELECT s.student_id
FROM students s
JOIN (
SELECT student_id
FROM courses
WHERE course_name IN ('数学', '英语')
GROUP BY student_id
HAVING COUNT(DISTINCT course_name) = 2
) selected_courses ON s.student_id = selected_courses.student_id;
```
这个查询的工作原理是首先找出所有选修了数学和英语的学生ID(subquery),然后从`students`表中选取这些学生的学号。`HAVING COUNT(DISTINCT course_name) = 2`确保每个学生选择了至少两门不同的课程(数学和英语)。
相关问题
MYSQL语句 成绩表包括所选课程和学生学号 每个学生可以选一门或多门课程 求至少同时选修课程1和课程2的学时的学号
在MySQL中,你可以使用`INNER JOIN`和`GROUP BY`以及`HAVING`来查询至少同时选修课程1和课程2的学生及其学时。假设你的成绩表名为`scores`,有`student_id`(学生ID)、`course_id`(课程ID)和`credit_hours`(学时)字段,那么SQL语句可能如下:
```sql
SELECT s.student_id, SUM(s.credit_hours) as total_hours
FROM scores s
WHERE s.course_id IN (1, 2)
GROUP BY s.student_id
HAVING COUNT(DISTINCT s.course_id) = 2;
```
这个查询做了以下几件事:
1. `WHERE s.course_id IN (1, 2)` 筛选出课程ID为1或2的成绩记录。
2. `GROUP BY s.student_id` 将结果按学生ID分组。
3. `SUM(s.credit_hours)` 计算每个学生的总学时。
4. `HAVING COUNT(DISTINCT s.course_id) = 2` 验证每个学生是否有两门不同的课程记录。
阅读全文
相关推荐

















