MySQL,对嵌套计数感到困惑

时间:2016-10-16 20:34:49

标签: mysql sql

这是表格:

  node.setOnDragDetected(new EventHandler<MouseEvent>() {
     @Override
     public void handle(MouseEvent event) {
        System.out.println("odDragDetected");

        double x = event.getX();
        double y = event.getY();
        x -= node.getTranslateX();
        y -= node.getTranslateY();
        dragVector = new Point2D(x, y);

        Dragboard db = node.startDragAndDrop(TransferMode.COPY_OR_MOVE);
        ClipboardContent cc = new ClipboardContent();
        cc.putString("Something");
        db.setContent(cc);
     }
  });

我无法弄清楚这个查询背后的逻辑

+------+--------+------+--------+
| 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);

如果count是一个聚合命令,它如何能够与另一个聚合相等,并在它是where条件时返回一个表?

1 个答案:

答案 0 :(得分: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;