您可以sum()
在内部使用聚合函数COALESCE()
。如果记录存在,则以下语法返回所有值的总和,否则返回0。语法如下。
select COALESCE(sum(yourColumnName2), 0) AS anyVariableName from yourTableName where yourColumnName1 like '%yourValue%';
为了理解上述语法,让我们创建一个表。创建表的查询如下。
mysql> create table SumDemo -> ( -> Words varchar(100), -> Counter int -> );
使用insert命令在表中插入一些记录。查询如下。
mysql> insert into SumDemo values('Are You There',10); mysql> insert into SumDemo values('Are You Not There',15); mysql> insert into SumDemo values('Hello This is MySQL',12); mysql> insert into SumDemo values('Hello This is not MySQL',14);
使用select语句显示表中的所有记录。查询如下。
mysql> select *from SumDemo;
以下是输出。
+-------------------------+---------+ | Words | Counter | +-------------------------+---------+ | Are You There | 10 | | Are You Not There | 15 | | Hello This is MySQL | 12 | | Hello This is not MySQL | 14 | +-------------------------+---------+ 4 rows in set (0.00 sec)
这是每当记录存在时给出总和的查询。
mysql> select COALESCE(sum(Counter), 0) AS SumOfAll from SumDemo where Words like '%hello%';
以下是输出。
+----------+ | SumOfAll | +----------+ | 26 | +----------+ 1 row in set (0.00 sec)
如果记录不存在,那么您将获得0。查询如下。
mysql> select COALESCE(sum(Counter), 0) AS SumOfAll from SumDemo where Words like '%End of MySQL%';
以下是输出。
+----------+ | SumOfAll | +----------+ | 0 | +----------+ 1 row in set (0.00 sec)