选择同时选择足球和篮球的学生

时间:2018-08-05 11:13:35

标签: sql group-by

我有一个这样的表course

studentName  courseName

 Alen        basketball
 Alen        football
 Alen        tennis
 Bob         tennis
 Dean        football
 Charlie     football
 Charlie     basketball

我想选择同时选择两者篮球和足球的学生。

预期输出:

studentName  courseName

 Alen        basketball
 Alen        football
 Alen        tennis
 Charlie     football
 Charlie     basketball

如何有效地做到这一点?

我当前正在使用此sql。它工作正常,但似乎很慢:

select * from course as ss1 where 
exists 
(select * from course as ss2 where ss2.studentName = ss1.studentName and ss2.courseName = 'basketball')
and exists
(select * from course as ss2 where ss2.studentName = ss1.studentName and ss2.courseName = 'football')
order by ss1.studentName desc

4 个答案:

答案 0 :(得分:2)

您可以尝试使用EXIST来代替使用JOIN来获取和比较相交的数据。

下面用sql-server编写的示例。

SELECT wholeStudents.*
FROM course wholeStudents
JOIN
  (SELECT DISTINCT StudentName
   FROM course
   WHERE CourseName IN ('basketball', 'football')
   GROUP BY StudentName 
   HAVING COUNT(1) =2) 
   AS disticnctStudents -- this table will only have a list of students selected both sports
ON (disticnctStudents.StudentName = wholeStudents.StudentName)

注意:根据这样的假设,studentName是唯一的,并且学生只能进行一项运动。

答案 1 :(得分:1)

select ss1.studentName, ss1.courseName c1, ss2.courseName c2 from course as ss1 
LEFT JOIN course as ss2 on ss1.studentName = ss2.studentName
where c1 != c2 and (c1 ='basketball' and c2 ='football')

选择学生姓名

select ss1.studentName from course as ss1 
LEFT JOIN course as ss2 on ss1.studentName = ss2.studentName
where ss1.courseName != ss2.courseName and (ss1.courseName ='basketball' and 
ss2.courseName ='football')

答案 2 :(得分:0)

  

选择*从课程WHERE中,课程名称=“篮球”或课程名称=   “足球”

万岁简单xD

答案 3 :(得分:0)

您可以使用2个简单的查询,然后找到两者的交集

SELECT studentName FROM course WHERE courseName = 'basketball'
INTERSECT
SELECT studentName FROM course WHERE courseName = 'football'

有关postgres的信息,请参见 http://www.postgresqltutorial.com/postgresql-intersect/

对于Oracle还是这样 https://www.techonthenet.com/oracle/intersect.php