2016-10-16 44 views
0

下面是表:MySQL的,困惑的嵌套计数

+------+--------+------+--------+ 
| sID | sName | GPA | sizeHS | 
+------+--------+------+--------+ 
| 123 | Amy | 3.9 | 1000 | 
| 234 | Bob | 3.6 | 1500 | 
| 345 | Craig | 3.5 | 500 | 
| 456 | Doris | 3.9 | 1000 | 
| 567 | Edward | 2.9 | 2000 | 
| 678 | Fay | 3.8 | 200 | 
| 789 | Gary | 3.4 | 800 | 
| 987 | Helen | 3.7 | 800 | 
| 876 | Irene | 3.9 | 400 | 
| 765 | Jay | 2.9 | 1500 | 
| 654 | Amy | 3.9 | 1000 | 
| 543 | Craig | 3.4 | 2000 | 
+------+--------+------+--------+ 

我想不通的逻辑是这样的查询背后究竟

select * 
from Student S1 
where (select count(*) from Student S2 
    where S2.sID <> S1.sID and S2.GPA = S1.GPA) = 
    (select count(*) from Student S2 
    where S2.sID <> S1.sID and S2.sizeHS = S1.sizeHS); 

这是返回什么:

+------+--------+------+--------+ 
| sID | sName | GPA | sizeHS | 
+------+--------+------+--------+ 
| 345 | Craig | 3.5 | 500 | 
| 567 | Edward | 2.9 | 2000 | 
| 678 | Fay | 3.8 | 200 | 
| 789 | Gary | 3.4 | 800 | 
| 765 | Jay | 2.9 | 1500 | 
| 543 | Craig | 3.4 | 2000 | 
+------+--------+------+--------+ 

count是一个聚合命令,它是否能够等于另一个聚合并在它是where条件时返回一个表?

回答

3

count(*)查询正在作为共同相关的子查询运行,它们都返回单个标量值(integer)。 您的主要查询没有任何它自己的聚合。

这两个count(*)查询返回两个数字,这两个数字在where条件下相互比较,这是完全合法的。

查询将评估为这样的事情:

select * 
from Student S1 
where (<count of students with the same GPA as this student>) 
     = 
     (<count of students with the same sizeHS as this student>); 

然后,例如,如果一个学生(表中的一个记录)的计数回来为56,那么where条件该记录将评估为:

select * 
from Student S1 
where 5 
     = 
     6; 
+0

很好的解释 – Andrew