如何在 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)
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言
C++
C#
MongoDB
MySQL
Javascript
PHP