我有一个查询基本上可以找出我的mysql表中的所有点。我使用的是Zend Framework 2,查询基本上是这样的:
public function GetFiveUsersWithHighestPoints($brandId,$startDate, $endDate)
{
$select = new Select();
$select->from(array("h" => $this->table));
$select->columns(array(
"id",
"userId",
"type",
"points",
"missionId",
"rewardId",
"brandId",
"goodsId",
"time",
));
$select->order("h.points desc");
$where = new Where();
$select->join(array("m" => "missions"), "h.missionId = m.id", array("missionId" => "id", "missionName" => "title", "missionAction" => "action"), Select::JOIN_LEFT);
if (!empty($journeyId)) {
$where->equalTo("m.journeyId", $journeyId);
} else {
$select->join(array("r" => "rewards"), "h.rewardId = r.id", array("rewardId" => "id", "rewardName" => "name"), Select::JOIN_LEFT);
}
$where->notEqualTo("h.points", 0);
$where->equalTo("h.brandId", $brandId);
$where->between("h.time", $startDate, $endDate);
//分页代码块。固定用法
$select->where($where);
return $this->historyTable->selectWith($select)->toArray();
}
现在我想要做的是所有的点都按用户ID进行分组,这基本上对应于每个用户在给定时间跨度内有多少点...我怎样才能总结所有每个UserId的点数,所以我得到这样的东西:
等。等
我在Zend Framework 2中编写查询时很新,我不知道接下来该做什么...
答案 0 :(得分:0)
如何使用SUM()
添加GROUP BY
列,例如:
use Zend\Db\Sql\Expression;
// Include a SUM() expression
$select->cols([
// Include existing columns
// etc...
// Add a SUM col
'pointsCount' => new Expression('SUM(h.points)'),
]);
// Add a GROUP BY
$select->group('h.userId');
然后,您可以在名称为pointsCount
的每个结果行中访问您所寻求的每个用户点数。