gpt4 book ai didi

mysql - 查询还返回值为 0 的列

转载 作者:行者123 更新时间:2023-11-30 00:59:46 24 4
gpt4 key购买 nike

我有两个表:

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

如何才能同时返回问题 id = 2 且计数为 0 的问题?

预期结果:

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

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

最佳答案

两个问题:

  1. 您必须使用外连接来获取没有答案的问题。

  2. 您遗漏了 GROUP BY 子句。


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

关于mysql - 查询还返回值为 0 的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20249077/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com