如何在 MySQL 中选择总和或 0(如果不存在记录)?
你可以在 COALESCE() 中使用聚合函数 sum()。以下语法返回所有记录的总和,否则返回 0。语法如下。
select COALESCE(sum(yourColumnName2), 0) AS anyVariableName from yourTableName where yourColumnName1 like '%yourValue%';
为了理解以上语法,我们来创建一个表。创建表的查询如下。
mysql> create table SumDemo -> ( -> Words varchar(100), -> Counter int -> ); Query OK, 0 rows affected (0.93 sec)
使用 insert 命令在表中插入一些记录。查询如下。
mysql> insert into SumDemo values('Are You There',10); Query OK, 1 row affected (0.16 sec) mysql> insert into SumDemo values('Are You Not There',15); Query OK, 1 row affected (0.13 sec) mysql> insert into SumDemo values('Hello This is MySQL',12); Query OK, 1 row affected (0.09 sec) mysql> insert into SumDemo values('Hello This is not MySQL',14); Query OK, 1 row affected (0.24 sec)
使用 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)
广告