如何計算 MySQL 表中的總數和 true 條件值?


為此,您可以使用 COUNT()。首先讓我們建立一個表 -

mysql> create table DemoTable
(
   Value int
);
Query OK, 0 rows affected (0.69 sec)

使用插入命令在表中插入一些記錄 -

mysql> insert into DemoTable values(10);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(NULL);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(20);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values(40);
Query OK, 1 row affected (0.16 sec)

使用 select 語句顯示錶中的所有記錄 -

mysql> select *from DemoTable;

這將產生以下輸出 -

+-------+
| Value |
+-------+
| 10    |
| NULL  |
| 20    |
| 40    |
+-------+
4 rows in set (0.00 sec)

以下是計算 MySQL 表中的總值和 true 條件值的查詢 -

mysql> select count(*) as TOTAL_COUNT,count(Value OR NULL) as CONDITION_TRUE from DemoTable;

這將產生以下輸出 -

+-------------+----------------+
| TOTAL_COUNT | CONDITION_TRUE |
+-------------+----------------+
|           4 |              3 |
+-------------+----------------+
1 row in set (0.00 sec)

更新於: 2019 年 9 月 24 日

93 次瀏覽

職業生涯的開端

完成課程獲得認證

開始吧
廣告
© . All rights reserved.