【发布时间】:2016-06-10 11:29:57
【问题描述】:
我有如下表结构:
品牌 => 历史
历史记录表包含以下列:
brandId, userId, points(对于每个品牌,用户得分多少分).. 我需要将他在历史表中两个日期之间得分的用户的所有积分相加。
查询将接受 4 个参数:userId、brandId、startDate、endDate... 以下输出类似于:
userId brandId points
1 64 155 sum of all points in between two dates specified by the parameter.
如果 BrandId 的传递值为 = null(即未传递)。如果在该 BrandId 和 UserId 的历史表中没有找到任何数据,查询也应该返回有关品牌和用户的全部数据......我已经在 Zend Framework 2 中编写了自己的查询,但它没有输出我想要的(仅返回实际在历史表中找到的记录)...
看起来像这样:
public function BrandWallBrandsById($userId,$brandId,$startDate,$endDate)
{
$select = new Select();
$select->from(array('p' => $this->table), array('id'));
$select->join(array('b' => 'brands'), 'p.brandId = b.id', array('id','name', 'cover', 'slogan', 'startDate', 'homepage','endDate','active'));
$select->columns(array(new Expression('SUM(p.points) as points'), "userId", "brandId"));
$select->order("p.points asc");
$select->group("p.brandId");
$where = new Where();
$where->notEqualTo("p.points", 0);
$where->notEqualTo("p.type",10);
$where->equalTo("p.userId", $userId);
$where->equalTo("p.brandId", $brandId);
$where->equalTo("b.active",1);
$where->between("p.time", $startDate, $endDate);
$select->where($where);
return $this->historyTable->selectWith($select)->toArray()[0];
}
请注意,查询一次只返回一条记录。我想写一个纯 SQL 语句,因为我认为它可能比这更容易... 有人可以帮帮我吗?
【问题讨论】:
标签: php mysql sql-server zend-framework zend-framework2