SQL - 如何过滤联接表中的多个行?

时间:2017-11-21 19:51:44

标签: mysql sql

我有一个名为Students的表和一个名为Courses的表以及一个表Student_Course,它通过student_id外国人在两者之间创建多对多关系密钥和course_id外键。

我正在尝试查询学生并过滤结果,只包括那些同时参加过"数学" AND"科学"课程。

这似乎应该是一个相当简单的任务,所以也许我错过了一些明显的东西。

提前谢谢

3 个答案:

答案 0 :(得分:1)

我想最简单的解决方案是

 select s.*
 from Student s
 join Student_Course sc on s.student_id = sc.student_id
 join Courses c on sc.course_id = c.course_id 
 where c.name in ('math', 'science')
 group by sc.student_id
 having count(distinct c.course_id) = 2

如果学生不能多次参加同一课程,则无需distinct。另一种解决方案是使用EXISTS,如下所示

 select *
 from Student s
 where exists (
   select 1
   from Student_Course sc
   join Courses c on sc.course_id = c.course_id 
   where s.student_id = sc.student_id and c.name = 'math'
 ) and exists (
   select 1
   from Student_Course sc
   join Courses c on sc.course_id = c.course_id 
   where s.student_id = sc.student_id and c.name = 'science'
 )

答案 1 :(得分:1)

使用sum,您可以获得所需的数据

select s.*
from Students s
join Student_Course sc on s.id = sc.student_id
join courses c on c.id = sc.course_id
group by s.id
having sum(c.name = 'Math')
and sum(c.name = 'Science')

答案 2 :(得分:0)

工作小提琴http://sqlfiddle.com/#!9/71e36b/1

//选择

select
 a.student_name,
 c.course_name
from
  Students a
  inner join Student_Course b on a.student_id = b.student_id
  inner join Courses c on b.course_id = c.course_id
 where
   c.course_name = 'Math' OR c.course_name = 'Science'

//架构

CREATE TABLE Students (
  student_id int(11) NOT NULL,
  student_name varchar(200) NOT NULL
);

CREATE TABLE Courses (
  course_id  int(11) NOT NULL,
  course_name varchar(200) NOT NULL
);

CREATE TABLE Student_Course   (
  student_id int(11) NOT NULL,
  course_id  int(11) NOT NULL
);

insert into Students (student_id, student_name) values (1, 'mike');
insert into Students (student_id, student_name) values (2, 'eugene');
insert into Students (student_id, student_name) values (3, 'paul');

insert into Courses (course_id, course_name) values(1, 'Math');
insert into Courses (course_id, course_name) values(2, 'Phys');
insert into Courses (course_id, course_name) values(3, 'Chemistry');
insert into Courses (course_id, course_name) values(4, 'Language');
insert into Courses (course_id, course_name) values(5, 'Science');

insert into Student_Course(student_id, course_id) values(1, 1);
insert into Student_Course(student_id, course_id) values(1, 2);
insert into Student_Course(student_id, course_id) values(1, 3);
insert into Student_Course(student_id, course_id) values(2, 1);
insert into Student_Course(student_id, course_id) values(3, 5);