如果 MySQL 中不存在记录,如何选择总和或 0?

mysqlmysqli database

您可以在 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)

相关文章