从多个表中检索相应的和非对应的值

时间:2016-06-10 11:29:58

标签: php mysql sql-server zend-framework zend-framework2

我有以下表结构:

品牌=>历史< =用户

Histories表包含以下列:

brandId,userId,指向(每个品牌用户得分数点数)。我需要在历史表中的两个日期之间为用户所得的所有积分求和。

查询将接受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语句,因为我认为它可能比这更容易... 有人可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

这是一个SQL语句,可以让你在SQL Server中得到你想要的东西,虽然我不熟悉zend-framework。

declare @startDate datetime, @endDate datetime, @userId int = null, @brandId int = null
set @startDate = '6/1/2016'
set @endDate = '6/9/2016'
set @userId = 1      --this can be NULL
set @brandId = 64    --this can be NULL

select
    userId,
    brandId, 
    sum(points) as points
from
    historyTable
where
    (@userId is null or userId = @userId)
    and (@brandId is null or brandId = @brandId)
    and dateColumn >= @startDate
    and dateColumn < dateadd(day,1,@endDate) 
group by
    userId, brandId