0
我有一個下表結構:檢索對應和非對應的值從多對多表
品牌=>瀏覽歷史< =用戶
史表包含下列:
brandId,用戶id,積分(每個品牌有多少積分用戶積分)。我需要將他在歷史表中的兩個日期之間得分的用戶的所有積分相加。
查詢將接受4個參數:用戶id,brandId,的startDate,結束日期...下面的輸出會是這樣的:
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語句,因爲我認爲它可能比這更容易... 有人可以幫我嗎?