将子查询转换为加入

时间:2011-02-16 05:34:01

标签: sql postgresql

我有三个表格,章节,课程和用于显示课程问题的问题。表结构在下面给出以供参考。

表“public.chapters”

  Column   |          Type          |                           Modifiers                           
-----------+------------------------+---------------------------------------------------------------
 id        | integer                | not null default nextval('chapters_chapter_id_seq'::regclass)
 chapter   | character varying(255) | not null
 course_id | integer                | 
 published | boolean                | default false

表“public.lessons”

   Column   |          Type          |                          Modifiers                          
------------+------------------------+-------------------------------------------------------------
 id         | integer                | not null default nextval('lessons_lesson_id_seq'::regclass)
 lesson     | character varying(255) | not null
 chapter_id | integer                | 
 published  | boolean                | default false

表“public.questions”

  Column   |          Type          |                            Modifiers                            
-----------+------------------------+-----------------------------------------------------------------
 id        | integer                | not null default nextval('questions_question_id_seq'::regclass)
 template  | character varying(255) | not null
 wording   | character varying(255) | not null
 lesson_id | integer                | not null

现在,我需要在一章中找到一些问题。所以,我使用以下查询。

select sum( num_of_questions ) as num_of_questions, 
       chapter_id 
 from ( select chapters.id as chapter_id,
               lesson_id, 
               count(*) as num_of_questions 
          from questions 
          JOIN lessons ON lessons.id = questions.lesson_id 
          JOIN chapters ON lessons.chapter_id = chapters.id 
      GROUP BY lesson_id, chapters.id  
      ORDER BY lesson_id, chapters.id) as foo 
group by  chapter_id;

如何将此查询转换为使用join而不是子查询。

1 个答案:

答案 0 :(得分:2)

使用:

  SELECT c.id as chapter_id,
         COUNT(*) as num_of_questions 
    FROM CHAPTERS AS c
    JOIN LESSONS AS l ON l.chapter_id = c.id
    JOIN QUESTIONS AS q ON q.lesson_id = l.id
GROUP BY c.id

不需要子查询 - 只需放宽GROUP BY子句。

原始查询中的ORDER BY对您没有任何作用,浪费资源 - 除非您使用LIMIT。