如何从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)
使用插入命令在表中插入一些记录。查询如下所示。
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 行受影响 (0.00 sec)
以下是在记录存在时给出总和的查询。
mysql> select COALESCE(sum(Counter), 0) AS SumOfAll from SumDemo where Words like '%hello%';
以下是输出结果。
+----------+
| SumOfAll |
+----------+
| 26 |
+----------+
1 行受影响 (0.00 sec)
如果记录不存在,则您将收到0。查询如下所示。
mysql> select COALESCE(sum(Counter), 0) AS SumOfAll from SumDemo where Words like '%End of MySQL%';
以下是输出结果。
+----------+
| SumOfAll |
+----------+
| 0 |
+----------+
1 行受影响 (0.00 sec)
阅读更多:MySQL 教程
极客教程