MySQL Query为所有学校学习的学生

时间:2016-06-17 13:47:20

标签: mysql

表由School_id和Student_name组成。

School_id   Student_Name
1           Raj
1           Tan
1           Brian
2           Raj
2           Brian
3           Raj
3           Tan

所以输出应该是Raj,因为Raj已经在所有学校学习过(1,2,3)。

4 个答案:

答案 0 :(得分:0)

如果已知不同学校的总数,则可以使用以下查询:

SELECT Student_Name
FROM mytable
GROUP BY Student_Name
HAVING COUNT(DISTINCT School_id) = 3

否则,您可以使用子查询代替3,如下所示:

SELECT COUNT(DISTINCT School_id)
FROM mytable

答案 1 :(得分:0)

使用count(distinct ...)获取子查询中的学校数量,将此数字连接到外部查询,在该查询中计算学生与之关联的学校数量,并在having子句中进行过滤。

SELECT Student_Name, COUNT(DISTINCT School_id), t1.school_count
FROM yourtable
INNER JOIN (SELECT COUNT(DISTINCT School_id) as school_count FROM yourtable) t1
GROUP BY Student_Name
HAVING COUNT(DISTINCT School_id) = t1.school_count

答案 2 :(得分:-2)

SELECT Student_Name
FROM Table 
WHERE 
    COUNT(School_id) = (
        SELECT COUNT(*) 
        FROM Table 
        GROUP_BY(School_id)
    )
GROUP BY (Student_Name)

答案 3 :(得分:-2)

  

编辑:添加说明

简单解决您的确切要求

通过检查所有上过所有学校的学生来检索学生姓名(列表中不同学校的数量必须等于学生参加的不同学校的数量)

SELECT Student_Name
FROM Table1
GROUP BY Student_Name
HAVING Count(School_ID) =
  (SELECT Count(School_ID) 
   FROM (SELECT DISTINCT School_ID FROM Table1) t1
  )