代码之家  ›  专栏  ›  技术社区  ›  xingbin

选择既选择足球又选择篮球的学生

  •  0
  • xingbin  · 技术社区  · 7 年前

    我有一张桌子 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 回复  |  直到 7 年前
        1
  •  1
  •   an33sh    7 年前

    而不是使用 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是唯一的,一个学生只能进行一次运动。

        2
  •  1
  •   Gireesh    7 年前
    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')
    
        3
  •  0
  •   Murad Alm.    7 年前

    从courseName=“basketball”或courseName所在的课程中选择*= “足球”

    简朴万岁xD

        4
  •  0
  •   Navid H    7 年前

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

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

    看这个给博士后看 http://www.postgresqltutorial.com/postgresql-intersect/

    或者这个给甲骨文 https://www.techonthenet.com/oracle/intersect.php