我的mysql数据库中有这个表
+-------+-----------+------------+
| name | upvotes | downvotes |
+-------+-----------+------------+
| Peter | 5 | 1 |
| Sam | 2 | 1 |
| Peter | 1 | 4 |
| Peter | 4 | 2 |
| Sam | 7 | 1 |
+-------+-----------+------------+
现在,我想添加每个名字的upvotes和downvotes。像这样:
+-------+-----------+------------+
| name | upvotes | downvotes |
+-------+-----------+------------+
| Peter | 10 | 7 |
| Sam | 9 | 2 |
+-------+-----------+------------+
我想通过downvotes减去upvotes(upvotes - downvotes)
+-------+-----------+
| name | total |
+-------+-----------+
| Peter | 3 |
| Sam | 7 |
+-------+-----------+
最后,我想根据总数按照降序顺序回复它们:
姓名:Sam
总计:7
赞成票:11
Downvotes:4
姓名:彼得
总计:3
赞成票:10
Downvotes:7
我知道这很多但是会感激不尽。提前谢谢
答案 0 :(得分:0)
您可以使用以下内容更精确
$query = "SELECT name, SUM(upvotes) AS upvotes, SUM(downvotes) AS downvotes FROM questions GROUP BY name;";
$result = mysqli_query($connection, $query);
您可以按名称分组,为您提供相同的答案。