代码之家  ›  专栏  ›  技术社区  ›  Mike

简单SQL返回计数而不使用子查询

  •  1
  • Mike  · 技术社区  · 17 年前

    我试图通过一个SQL语句来获取课程注册学生的数量,但不使用子查询。到目前为止,我只能用子查询来解决这个问题。还有别的办法吗?

    考虑以下数据库设置:

    create table student (id integer not null primary key);
    create table course_enrolment (student integer not null references student, course integer not null);
    insert into student values (1);
    insert into student values (2);
    insert into student values (3);
    insert into course_enrolment values (2,20);
    insert into course_enrolment values (2,30);
    insert into course_enrolment values (3,10);
    

    我想知道参加课程的学生人数。在这种情况下,是2。

    我可以使用子查询轻松实现这一点:

    选择count(*)from(select distinct student from course\u enrollment)作为数据;

    我想在不使用子查询的情况下获取计数。

    我正在使用PostgreSQL 8.3,但我正在寻找一个不可知供应商的解决方案。

    7 回复  |  直到 10 年前
        1
  •  8
  •   David M    17 年前

    这个怎么样?

    SELECT  course, COUNT(DISTINCT student)
    FROM    course_enrolment
    GROUP BY course
    

    这给了每个课程的学生。如果您只想获得任何课程的注册总数:

    SELECT  COUNT(DISTINCT student)
    FROM    course_enrolment
    

    我相信这是所有的ANSI标准SQL,所以应该在大多数地方工作。

        2
  •  2
  •   Marc Gravell    17 年前

    我不知道Postgres,但在SQL Server上:

    SELECT COUNT(DISTINCT STUDENT) FROM COURSE_ENROLMENT
    
        3
  •  2
  •   campo    17 年前

    我对PostgreSQL不太了解,但我会这样做,MS SQL Server…

    select count(distinct student)
    From course_enrolment
    
        4
  •  1
  •   soulmerge    17 年前
    SELECT COUNT(DISTINCT STUDENT) FROM COURSE_ENROLMENT
    
        5
  •  1
  •   Anton Gogolev    17 年前

    这是按课程选择学生:

    select course, count(*) as students 
    from course_enrolment
    group by course
    

    这只是为了统计学生人数(希望不是可怕的特定于SQL Server)

    select count(distinct student) from course_enrolment
    
        6
  •  1
  •   user80168    17 年前

    真正的问题是,为什么不使用子查询?

    一般来说,每个人的回答都是正确的:

    select count(distinct student) from course_enrolment
    

    但是,对于大量的学生/课程来说,PostgreSQL 8.4之前版本中的这种类型的查询会很慢。更快的方法是:

    select count(*) from (select student from course_enrolment group by student);
    

    但它使用子查询——出于某种原因,您不希望使用子查询。

        7
  •  0
  •   sree    10 年前
    select COUNT(distinct student) from course_enrolment