在 MySQL 中计算正反投票数?

mysqlmysqli database

要计算正反投票数,可以使用 CASE 语句和聚合函数 SUM()。

首先我们创建一个表 −

mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Vote int
);
Query OK, 0 rows affected (1.70 sec)

使用 insert 命令在表中插入一些记录 −

mysql> insert into DemoTable(Vote) values(-10);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable(Vote) values(100);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(Vote) values(45);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(Vote) values(-6);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(Vote) values(-1000);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(Vote) values(450);
Query OK, 1 row affected (0.14 sec)

以下是使用 select 语句显示表中的所有记录的查询 −

mysql> select *from DemoTable;

这将产生以下输出 −

+----+-------+
| Id | Vote  |
+----+-------+
| 1  | -10   |
| 2  | 100   |
| 3  | 45    |
| 4  | -6    |
| 5  | -1000 |
| 6  | 450   |
+----+-------+
6 rows in set (0.00 sec)

以下是计算赞成和反对票数的查询 −

mysql> select sum(case when Vote > 0 then 1 else 0 end) as Number_Of_Positive_Votes,
sum(case when Vote < 0 then 1 else 0 end) as Number_Of_Negative_Votes
from DemoTable;

这将产生以下输出 −

+--------------------------+--------------------------+
| Number_Of_Positive_Votes | Number_Of_Negative_Votes |
+--------------------------+--------------------------+
| 3                        | 3                        |
+--------------------------+--------------------------+
1 row in set (0.00 sec)

相关文章