SQL:存在的位置 - >比较两个表并检查它们是否具有相同的行数

时间:2017-10-14 13:47:49

标签: mysql sql compare

我的SQL知识已经结束了。我有一个问题,我想检查两个表是否有相同的行数。

一个例子可能是我想向所有学校展示椅子数量与学生人数相同的学校。我的伪代码看起来像这样:

SELECT * FROM schools WHERE
  ((SELECT COUNT(*) FROM students) = (SELECT COUNT(*) FROM chairs));

或使用伪计算:students - chairs = 0;

SELECT * FROM schools WHERE
  ((SELECT COUNT(*) FROM students) - (SELECT COUNT(*) FROM chairs) = 0);

是否可以使用SQL这样的构造,如果是这样的话?

1 个答案:

答案 0 :(得分:2)

您的方法似乎有点不正统,但您可以使用相关子查询来执行此操作:

SELECT s.*
FROM schools s.
WHERE ( (SELECT COUNT(*) FROM students st WHERE st.school_id = s.school_id) =
        (SELECT COUNT(*) FROM chairs c WHERE c.school_id = s.school_id)
      );

我更倾向于在聚合后进行加入:

select st.school_id
from (SELECT st.school_id, COUNT(*) as cnt
      FROM students st 
      GROUP BY st.school_id
     ) st JOIN
     (SELECT c.school_id, COUNT(*) as cnt
      FROM chairs c
      GROUP BY c.school_id
     ) c
     ON st.school_id = c.school_id AND st.cnt = c.cnt;

两个版本略有不同。此版本仅返回至少有一名学生(和主席)的学校ID。

编辑:

我应该注意,如果你只是想知道两个表是否有相同的行数,你可以在SELECT中返回一个布尔值:

SELECT ( (SELECT COUNT(*) FROM chairs c) =
         (SELECT COUNT(*) FROM students st)
       ) as num_rows_same_flag

由于schools表的存在,我认为你希望学校的每个学校都有相同的数量。