php - Retrieve corresponding and non corresponding values from many to many table
I have a following table structure:
Brands => Histories <= Users
Histories table contains following columns:
brandId, userId, points (for each brand how many points user scored points).. I need to sum all the points for user for which he scored in between two dates in history table.
The query would accept 4 parameters: userId, brandId, startDate, endDate... The following output would be something like:
userId brandId points
1 64 155 sum of all points in between two dates specified by the parameter.
If the passed value of BrandId is = null (ie. not passed). Query should return as well whole data about the brand and user if it doesn't finds any data in history table on that BrandId and UserId... I have written my own query in Zend Framework 2 but it doesn't outputs that I want (returns only records that are actually found in history table)...
It looks like this:
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];
}
Note that the query only returns single record at a time when its called.. I wanna write a pure SQL statement, since I think it might be easier than this... Can someone help me out?
Answer
Solution:
Here is a SQL statement to get you what you want in SQL Server, though i'm not familiar with zend-framework.