我制作了一个MySQL数据库。该字段为:ID:NAME:QUANTITY
我确实有例如:
ID:NAME:QUANTITY
1: APPLE: 3
1: APPLE: 4
2: BANANA: 1
2: BANANA: 2
我希望得到:
而不是这个输出APPLE 7
BANANA 3
我尝试了很多东西,但我一次又一次地失败了。你们有解决方案吗?
我的代码是:
public function getList($user_id, $recept_id) {
$return = array();
$sql = "select * from list";
$result = mysqli_query($this->link, $sql);
while ($row = mysqli_fetch_assoc($result)) {
$return[] = $row;
}
return($return);
答案 0 :(得分:3)
只需在查询中汇总数量。
SELECT `NAME`, SUM(`QUANTITY`) as QUANTITY FROM list GROUP BY `NAME`;
代码:
$return = array();
$sql = "SELECT `NAME`, SUM(`QUANTITY`) as QUANTITY FROM list GROUP BY `NAME`";
$result = mysqli_query($this->link, $sql);
while ($row = mysqli_fetch_assoc($result)) {
$return[] = $row;
}
return($return);
答案 1 :(得分:-2)
编辑总和而非计数。
使用SUM
函数,类似这样的函数
SELECT NAME,SUM(QUANTITY) as QUANTITY FROM list GROUP BY NAME ORDER BY QUANTITY DESC;