在SQL中,如何显示正在学习多个科目的学生?

时间:2012-01-01 21:06:41

标签: mysql sql

例如 - 表名= TABLE

StudentID | SubCode | SubName
-----------------------------
    1          M1       Math
    1          S1       Science
    1          E1       English
    2          H1       History
    3          G2       Geography
    4          M1       Math    

我们可以这样显示答案吗?

studentid | SubCode | SubName
---------------------------------
    1          M1       Math
    1          S1       Science
    1          E1       English

2 个答案:

答案 0 :(得分:6)

带有IN()子句的HAVING子查询应该这样做:

SELECT * 
FROM table
WHERE StudentID IN (
  SELECT 
    StudentID
  FROM table
  GROUP BY userid
  HAVING COUNT(*) > 1
)

答案 1 :(得分:2)

SELECT DISTINCT T1.*
  FROM YourTable AS T1
       INNER JOIN YourTable AS T2
          ON T1.StudentID = T2.StudentID
             AND T1.SubCode <> T2.SubCode;