简体   繁体   English

查询还会返回值为0的列

[英]Query also returns column with value 0

I have two tables: 我有两个表:

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

And my query: 而我的查询:

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;

Result: 结果:

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

How could it do to return also question id = 2 with 0 count ? 如何返回还等于0的id = 2的问题?

Expected result: 预期结果:

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

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

Two problems: 两个问题:

  1. You have to use an outer join to get questions with no answers. 您必须使用外部联接来获取没有答案的问题。

  2. You left out the GROUP BY clause. 您忽略了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 演示

不要使用内部联接来选择所有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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 MYSQL查询,因此如果其他表中没有值,它也会返回值 - MYSQL query so it also returns values if has no value in the other table 将结果分组的MySQL语句,但还返回组中另一列的最低和最高值 - MySQL statement that groups results, but also returns the lowest and the highest value of another column from within the group 如何在列中搜索值,并在单个SQL查询中获取列数 - How do I search for a value in a column and also get count of the column in a single SQL query SQL 查询查找包含在另一列中也出现的列中的值的行? - SQL query to finds rows containing a value in a column that also appears in another column? SQL查询为PHP中的ID列返回不正确的值 - SQL query returns incorrect value for ID column in PHP mysql查询返回第一列中所有其他列的值 - mysql query returns the value in the first column for all the other columns 查询以获取一个表的值,该值不在另一表的字符串列中,还小于特定的日期时间值 - Query to get values of one table which are not there in string column of another table, also less than a particular datetime value 查询返回空值 - query returns empty value 具有日期范围选择的MySQL查询,但当另一列重复时,还需要获取一列的最大值 - MySQL query with a date range selection but also need to grab the highest value of one column when another column has duplicates 查询返回关于列的错误信息 - Query returns false information on column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM