查询还返回值为0的列

时间:2013-11-27 17:24:29

标签: mysql sql

我有两张桌子:

tb_question
**id_quest**    | **desc_quest**
    1           | How do you do...?
    2           | How are you...?

tb_answer
**id_quest** | **date_answer**
    1        |    2013/11/25
    1        |    2013/11/26
    1        |    2013/11/27

我的疑问:

SELECT 
q.id_quest,
q.desc_quest,
COUNT(a.id_quest) as total_answer -- count total answer by question

FROM tb_question q
INNER JOIN tb_answer a
ON q.id_quest = a.id_quest;

结果:

ID_QUEST  | DESC_QUEST              | TOTAL_ANSWER
   1      | How do you do...?       |    3

如何以0计数返回问题id = 2?

预期结果:

ID_QUEST  | DESC_QUEST              | TOTAL_ANSWER
   1      | How do you do...?       |    3
   2      | How are you...?         |    0

http://sqlfiddle.com/#!2/3bfe7/1

2 个答案:

答案 0 :(得分:0)

两个问题:

  1. 您必须使用外部联接才能获得没有答案的问题。

  2. 您遗漏了GROUP BY条款。


  3. SELECT 
        q.id_quest,
        q.desc_quest,
        COUNT(a.id_quest) as total_answer
    FROM tb_question q
    LEFT OUTER JOIN tb_answer a ON q.id_quest = a.id_quest
    GROUP BY q.id_quest
    

    DEMO

答案 1 :(得分:0)

不要使用内部联接来选择所有idquest,内部联接以生成表的子集

SELECT tbq.id_quest,tbq.desc_quest,COUNT(tba.id_quest) FROM tb_question tbq LEFT OUTER JOIN tb_answer tba ON tba.id_uest=tbq.id_quest GROUP BY tbq.id_quest ORDER BY tbq.id_quest