2016-10-16 43 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