这是表格:
+------+--------+------+--------+
| 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 条件时返回一个表?
最佳答案
count(*)
查询作为相关的子查询运行,它们都返回一个标量值(整数
)。
您的主查询本身没有任何聚合。
两个 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>);
然后,例如,如果学生的计数(表中的一条记录)返回为 5
和 6
,则 where
该记录的条件将被评估为:
select *
from Student S1
where 5
=
6;
关于MySQL,对嵌套计数感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40075155/