如何使用MySQL计算现有和不存在的值?

时间:2012-11-15 06:11:00

标签: mysql sql count

我是MySQL的新手。

我有一张带有答案ID的表格。 答案可能如下所示:a1, a2, a3 ...,但由于某些问题,有些问题是NULL,有些问题是空白的,有些则是1 a等问题。

现在我想明确计算出a1 a2 a3的ID数。但是如何才能做到这一点,留下像NULL,空白和垃圾这样的人。

输出应该如下所示

atype count 
a1      45
a2       0
a3      56

如果特定答案没有行条目,则计数应为0.

3 个答案:

答案 0 :(得分:3)

解决方案1:两次查询

您应该使用包含所需(正确)答案类型的表格:

| id | answer |
---------------
| 1  | a1     |
| 2  | a2     |
etc.

然后,您可以计算表格中实际存在的结果:

SELECT atype, COUNT( * ) cnt FROM answers JOIN mytable 
    ON mytable.atype=answers.answer GROUP BY answers.answer;

(将mytable替换为相应的表名)。

当然,这只会返回现有结果。要计算零行,您可以查找表中未显示的答案:

SELECT answer, '0' AS cnt FROM answers WHERE answer NOT IN(
    SELECT DISTINCT answer FROM answers JOIN mytable WHERE answer=mytable.atype );

Here is an example.

解决方案2:计数器表

另一种方法是使用计数器表:

| id | answer | cnt |
---------------------
| 1  | a1     | 0   |
| 2  | a2     | 0   |
etc.

然后每次想要计算结果时,请执行以下操作:

UPDATE answers SET cnt=0;

UPDATE answers SET cnt=
    (SELECT cnt FROM 
        ((SELECT answers.answer, COUNT(*) AS cnt 
          FROM answers JOIN mytable ON answers.answer=myTable.aType 
          GROUP BY answers.answer) AS tbl) 
     WHERE answers.answer=tbl.answer) 
WHERE EXISTS 
    (SELECT cnt FROM 
        ((SELECT answers.answer, COUNT(*) AS cnt
          FROM answers JOIN mytable ON answers.answer=mytable.atype
          GROUP BY answers.answer) AS tbl) 
     WHERE answers.answer=tbl.answer);

这会更新答案表中的计数器值,您只需SELECT * FROM answers ORDER BY answer即可获得结果。

但请注意:我认为第二个版本虽然方便,但由于需要所有子查询,因此比第一个版本需要更多的计算能力。

Here is this example(UPDATE语句位于左侧!)

解决方案3:写入时更新

在我看来,像你这样的用例最好和性能最差的解决方案是创建一个像我在#2中描述的那样的计数器表,但在用户回答时更新计数器值问题,而不是每次想要知道计数时重新计算所有条目。

这很容易做到。每次正确回答问题时,请在answers表中增加计数器:

UPDATE answers SET cnt=cnt+1 WHERE answers.answer='a1';

同样,您的查询将是

SELECT * FROM answers ORDER BY answer;

答案 1 :(得分:0)

select a.atype,count(*) as `Count`
from
 (select 'a1' as atype union all
  select 'a2' as atype union all
  select 'a3' as atype )a
left join <your_table> b
on a.atype =b.atype
group by atype

答案 2 :(得分:0)

我试图提出所有主要选择,每个查询后面跟着演示链接。链接包含说明

select AType,count(*) as Count from tb2
where atype!='' and atype is not null and atype!='0' group by atype

Link1 (Best One) To count answers of each (existing) type other than balank 0 and null

select (select count(id) from tb2 where atype='a1') as A1,(select count(id) from
tb2 where atype='a2') as A2,(select count(id) from tb2 where atype='a3') as A3;

Link2 (Simple and most suitable for you) count answers of types a1,a2 or a3 only (my older method to get similar results to link3)

select AType,count(*) as Count from tb2
where atype in('a1','a2','a3') group by atype

Link3 count answers of types a1,a2 or a3 only.

第一个和最后一个链接不考虑数据中完全不存在的那些类型。例如,如果没有类型a2的答案,那么第一个和第三个查询将只告诉类型为a1和a3的答案数,并且不会提及atype = a2的答案。但是第二个查询确实如此。